package cn.iune.erp.inventory;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Date;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.draw.LineSeparator;
import com.justep.baas.Utils;

import cn.iune.common.response.MapMessage;
import cn.iune.erp.setting.IParamSettingService;
import cn.iune.erp.setting.ISettingService;
import cn.iune.erp.setting.ParamSetting;




@Transactional
@Service
public class InventoryServiceImpl implements IInventoryService {
	
	private final Logger log = LogManager.getLogger(getClass());
	
	
	@Autowired
	private IFileItemService fileItemService;
	@Autowired
	private IFileStorageService fileStorageService;
	@Autowired
	private IStorageRecordService storageRecordService;
	@Autowired
	private IStorageRecordDetailService storageRecordDetailService;
	@Autowired
	private IStorageItemService storageItemService;
	
	@Autowired
	private ISettingService settingService;
	
	@Autowired
	private IParamSettingService paramSettingService;

	@Autowired
	private IItemBatchService itemBatchService;
	
	@Autowired
	private IStorageItemBatchService storageItemBatchService;
	
	@Autowired
	private IStocktakingService stocktakingService;
	@Autowired
	private IStocktakingDetailService stocktakingDetailService;

	@Autowired
	private IStorageLedgerService storageLedgerService;
	@Autowired
	private IStorageLedgerDetailService storageLedgerDetailService;
	

	
	
	///////////////////////////////////////////////////////////////////
	/////////////////////////////////////////////////////////////////////
	
	//MRP计算
	//计算原则：
	//1、选择的仓库是要求参加MRP运算
	//2、安全库存量（最小库存量）为0不参加计算
	//3、按单一工厂计算
	//4、返回table
	///////////////////////////////////////////////////////////////////
	

	@Override
	public StorageRecord getByID(String fID) {
		return storageRecordService.getByID(fID);
	}
	
	
	//提交出入库单
	@Override
	@Transactional
	public Map<String,Object> storageLedgerConfirm(String rowID, String cUsercode, String cUsername, String userId, String employeeNo, String employeeName){
		
		StorageLedger obj = storageLedgerService.getByID(rowID);
		
		MapMessage mapMessage = new MapMessage(obj.getfID(),obj.getRecordNo(),obj.getBillType(),obj.getBillTypeName()
				,MapMessage.STATUSINFO_SUCCESS_CODE//"http://www.iune.cn"
				,MapMessage.STATUSINFO_SUCCESS_MSG//"操作成功！"
				,MapMessage.STATUSINFO_SUCCESS_INFO//"操作成功！"
				,MapMessage.STATUSINFO_SUCCESS_FLAG//"success"
				);
		
		if("confirm".equals(obj.getAudit())){
			return mapMessage.toMap();
		}
		
		//验证数据完整性和有效性（已经放在前台处理）
		
		//然后审核主表
		storageLedgerService.confirm(rowID);
		
		//自动审核
		if(obj.getFlowType()==0){
			Map<String,Object> map = this.storageLedgerAgreeIt(rowID, cUsercode, cUsername, userId, employeeNo, employeeName);
			mapMessage.fromMap(map);
		}
		
		return mapMessage.toMap();
	}
	
	//撤回出入库单
	@Override
	@Transactional
	public Map<String,Object> storageLedgerActive(String rowID){
		StorageLedger obj = storageLedgerService.getByID(rowID);
		
		MapMessage mapMessage = new MapMessage(obj.getfID(),obj.getRecordNo(),obj.getBillType(),obj.getBillTypeName()
				,MapMessage.STATUSINFO_SUCCESS_CODE//"http://www.iune.cn"
				,MapMessage.STATUSINFO_SUCCESS_MSG//"操作成功！"
				,MapMessage.STATUSINFO_SUCCESS_INFO//"操作成功！"
				,MapMessage.STATUSINFO_SUCCESS_FLAG//"success"
				);
		
		if("confirm".equals(obj.getAudit())){
			return mapMessage.toMap();
		}

		//然后审核主表
		storageLedgerService.active(rowID);
		
		return mapMessage.toMap();
	}
	
	
	//审核出入库单（改造为主从表不关联审核）
	@Override
	@Transactional
	public Map<String,Object> storageLedgerAgreeIt(String rowID, String cUsercode, String cUsername, String userId, String employeeNo, String employeeName){
		
		StorageLedger sr = storageLedgerService.getByID(rowID);

		MapMessage mapMessage = new MapMessage(sr.getfID(),sr.getRecordNo(),sr.getBillType(),sr.getBillTypeName()
				,MapMessage.STATUSINFO_SUCCESS_CODE//"http://www.iune.cn"
				,MapMessage.STATUSINFO_SUCCESS_MSG//"操作成功！"
				,MapMessage.STATUSINFO_SUCCESS_INFO//"操作成功！"
				,MapMessage.STATUSINFO_SUCCESS_FLAG//"success"
				);
		
		//判断检验状态
		
		List<StorageLedgerDetail> srds = storageLedgerDetailService.getByMasterID(rowID);
		
		//首先审核从表
		for(StorageLedgerDetail srd : srds){
			System.out.println("storageLedgerAgreeIt-->>"+srd.getItemName());
			this.posting(srd, userId);
		}
		
		//然后审核主表
		storageLedgerService.agreeIt(rowID,cUsercode,cUsername,userId);

		
		return mapMessage.toMap();

	}
	
	//反审核出入库单
	@Override
	@Transactional
	public Map<String,Object> storageLedgerUnAgree(String rowID, String cUsercode, String cUsername, String userId, String employeeNo, String employeeName){
		//判断是否可以撤销
		
		StorageLedger sr = storageLedgerService.getByID(rowID);
		MapMessage mapMessage = new MapMessage(sr.getfID(),sr.getRecordNo(),sr.getBillType(),sr.getBillTypeName()
				,MapMessage.STATUSINFO_SUCCESS_CODE//"http://www.iune.cn"
				,MapMessage.STATUSINFO_SUCCESS_MSG//"操作成功！"
				,MapMessage.STATUSINFO_SUCCESS_INFO//"操作成功！"
				,MapMessage.STATUSINFO_SUCCESS_FLAG//"success"
				);

		
		List<StorageLedgerDetail> srds = storageLedgerDetailService.getByMasterID(rowID);
		for(StorageLedgerDetail srd : srds){
			System.out.println("storageLedgerUnAgree-->>"+srd.getItemName());
			this.posting(srd, userId);
		}
		
		//然后审核主表
		storageLedgerService.unAgree(rowID);
		
		return mapMessage.toMap();

	}

	//关闭出入库单
	@Override
	@Transactional
	public Map<String,Object> storageLedgerClose(String rowID){
		StorageLedger obj = storageLedgerService.getByID(rowID);
		
		MapMessage mapMessage = new MapMessage(obj.getfID(),obj.getRecordNo(),obj.getBillType(),obj.getBillTypeName()
				,MapMessage.STATUSINFO_SUCCESS_CODE//"http://www.iune.cn"
				,MapMessage.STATUSINFO_SUCCESS_MSG//"操作成功！"
				,MapMessage.STATUSINFO_SUCCESS_INFO//"操作成功！"
				,MapMessage.STATUSINFO_SUCCESS_FLAG//"success"
				);

		//首先审核从表
		
		//然后审核主表
		int rtn = storageLedgerService.close(rowID);
		if (rtn != 0){
			mapMessage.setStatusCode(MapMessage.STATUSINFO_FAILURE_CODE);
			mapMessage.setStatusMsg(MapMessage.STATUSINFO_FAILURE_MSG);
			mapMessage.setStatusInfo(MapMessage.STATUSINFO_FAILURE_INFO);
			mapMessage.setStatusFlag(MapMessage.STATUSINFO_FAILURE_FLAG);
			return mapMessage.toMap();
		}
		
		return mapMessage.toMap();
	}

	//打开出入库单
	@Override
	@Transactional
	public Map<String,Object> storageLedgerOpen(String rowID){
		StorageLedger obj = storageLedgerService.getByID(rowID);
		
		MapMessage mapMessage = new MapMessage(obj.getfID(),obj.getRecordNo(),obj.getBillType(),obj.getBillTypeName()
				,MapMessage.STATUSINFO_SUCCESS_CODE//"http://www.iune.cn"
				,MapMessage.STATUSINFO_SUCCESS_MSG//"操作成功！"
				,MapMessage.STATUSINFO_SUCCESS_INFO//"操作成功！"
				,MapMessage.STATUSINFO_SUCCESS_FLAG//"success"
				);

		//然后审核主表
		int rtn = storageLedgerService.open(rowID);
		if (rtn != 0){
			mapMessage.setStatusCode(MapMessage.STATUSINFO_FAILURE_CODE);
			mapMessage.setStatusMsg(MapMessage.STATUSINFO_FAILURE_MSG);
			mapMessage.setStatusInfo(MapMessage.STATUSINFO_FAILURE_INFO);
			mapMessage.setStatusFlag(MapMessage.STATUSINFO_FAILURE_FLAG);
			return mapMessage.toMap();
		}
		
		return mapMessage.toMap();
	}


	@Transactional
	@Override
    public void afterInsert(StorageRecordDetail obj){
		//更新主表合计
		//插入
		
    }
	
	@Transactional
	@Override
    public void beforeDelete(String fID){
		//StorageRecordDetail obj = storageRecordDetailDao.getByID(fID);
   	
    }
	

	//库存记账（审核）
	//库存记账（反审核）
	//使用同一个函数(数值变成负数就可以啦)
	@Transactional
	private StorageItem bookkeeping(			
			String revOpay 
			,String storageID
			,String itemID
			
			,BigDecimal itemQuantity
			,BigDecimal pieceQuantity 
			,BigDecimal costingAmount

			,String batchNo
			,String batchDescribe
			
			,String storeNo
			,String projectNo
			
			,int frozenFlag

			,String userId 
			,String enterpriseNo 
			,String enterpriseName 
			) {
		
		///////////////////////////////////////////////////////////////////////
		FileStorage fileStorage = fileStorageService.getByID(storageID);
		if(fileStorage==null) {
			log.info("仓库档案不存在！");
			return null;
		}
		//仓库ID
		String storehouseID = fileStorage.getStorageFullID().split("/")[1];
		///////////////////////////////////////////////////////////////////////
		
		if("I".equals(revOpay)) {
			//入库

			//1、更新仓库总账
			//StorageItem storageItem = storageItemService.storeRegister(obj.getStorageID(), storehouseID, obj.getItemID(), obj.getItemQuantity(), obj.getCostingAmount(), obj.getPieceQuantity(), obj.getEnterpriseNo(), obj.getEnterpriseName(), obj.getUserId());
			StorageItem storageItem = storageItemService.storeRegister(storageID, storehouseID, itemID, itemQuantity, costingAmount, pieceQuantity, enterpriseNo, enterpriseName, userId);

			//3、更新批号管理数量（如果启用批号管理）出库追踪入库
			/*
			 * N:不需要批号管理
			 * W:仅需警告
			 * Y:需要不检查库存
			 * T:需要且检查库存
			 */

			if (Utils.isNotEmptyString(batchNo) && !"********************".equals(batchNo)){
				//storageItemBatchService.storeRegister(obj.getStorageID(), storehouseID, obj.getItemID(), obj.getBatchNo(), obj.getItemQuantity(), obj.getPieceQuantity(),obj.getEnterpriseNo(),obj.getEnterpriseName(),obj.getUserId());
				storageItemBatchService.storeRegister(storageID, storehouseID, itemID, batchNo, itemQuantity, costingAmount, pieceQuantity, enterpriseNo, enterpriseName, userId);
			}

			//启用项目库存管理
			if (Utils.isNotEmptyString(projectNo)){
				//是否产生项目库表还需论证
			}
			
			//是否更新主档
			//if(mainFlag==1) {
				///////////////////////////////////////////////////////////////////////
				
				//2、更新物料总账（公司级，如果是调拨类的单据，则不调用此函数）
				fileItemService.storeRegister(itemID, itemQuantity, costingAmount, pieceQuantity);
				
				/*
				//登记上级物料（如果本级是SKU等级）
				String fParent = fileItem.getfParent();
				if(fParent!=null) {
					storageItemService.storeRegister(storageID, fParent, srd.getBatchNo(), srd.getAccountQuantityI(), accountPieceQuantity,srd.getEnterpriseNo(),srd.getEnterpriseName(),srd.getUserId());
					fileItemService.storeRegister(srd.getItemID(), srd.getAccountQuantityI(), accountPieceQuantity, costingAmount);
				}
				*/

				//3、更新批号管理数量（如果启用批号管理）出库追踪入库
				/*
				 * N:不需要批号管理
				 * W:仅需警告
				 * Y:需要不检查库存
				 * T:需要且检查库存
				 */

				if (Utils.isNotEmptyString(batchNo) && !"********************".equals(batchNo)){
					itemBatchService.storeRegister(batchNo, batchDescribe, itemID, itemQuantity, pieceQuantity, enterpriseNo, enterpriseName);
				}
			//}

			//////////////////////////////////////////////////////////////////////////////
			/*
			//TODO:（序列号管理--单件管理）
			String storeNo = srd.getStoreNo();
			if (storeNo!=null
					&& !srd.getStoreNo().equals("********************")
					&& !srd.getStoreNo().equals("")
					){
				//分解字符串
				String[] serialNumbers = storeNo.split(",");
				for(int i=0;i<serialNumbers.length;i++){
					String serialNumber = serialNumbers[i];
					if(serialNumber!=null && !"".equals(serialNumber)){
//						ItemStoreUtil isu = new ItemStoreUtil();
						ItemStore is = itemStoreService.getByNo(srd.getItemID(), serialNumber, srd.getEnterpriseNo());
						//判断序号是否存在，不存在则报错
						if(is!=null){
							//登记序列号移动轨迹
							
							itemStoreDetailService.insert(fID, serialNumber, itemID, systemCode, billType, billTypeName, orderDate, typeFrom, typeLabelFrom, placeIDFrom, placeNoFrom, placeShortFrom, placeNameFrom, typeTo, typeLabelTo, placeIDTo, placeNoTo, placeShortTo, placeNameTo, factoryNo, factoryName, employeeNo, employeeName, departmentNo, departmentName, origin, originName, originNo, userId, enterpriseNo, enterpriseName, fMasterID, 0);
							
						}else{
							try {
								throw new Exception("序列号："+serialNumber+"档案不存在，请建立档案。");
							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					}
				}
//				ItemStoreUtil isu = new ItemStoreUtil();
//				ItemStore is = isu.getByNo(srd.getItemNo(), serialNumber, srd.getEnterpriseNo());
//				isu.pickRegister(srd.getStoreNo(), srd.getItemNo(), srd.getItemDescribe(),srd.getRationSize(), srd.getUnitCode(), srd.getUnitName(), srd.getBatchNo(), accountQuantity, accountPieceQuantity, srd.getAbcGrade(), srd.getOrderWeight(), srd.getOrderSize(),srd.getItemWeight(),srd.getItemSize(), srd.getEnterpriseNo(), srd.getEnterpriseName());
				//仓库序（列）号管理
//				StorageItemStoreUtil sisu = new StorageItemStoreUtil();
//				sisu.pickRegister(storageNo, storageName, srd.getItemNo(), srd.getItemDescribe(), srd.getRationSize(), srd.getUnitCode(), srd.getUnitName(), accountQuantity, accountPieceQuantity, floorNo, srd.getStoreNo(),srd.getBarCode(),srd.getBatchNo(), factoryNo,factoryName, srd.getEnterpriseNo(),srd.getEnterpriseName());

			}
			*/
			///////////////////////////////////////////////////////////////////////
			
			return storageItem;
		}
		
		if("O".equals(revOpay)) {
			//出库
			
			//1、更新仓库总账
			//StorageItem storageItem = storageItemService.pickRegister(obj.getStorageID(), storehouseID, obj.getItemID(), obj.getItemQuantity(), obj.getCostingAmount(), obj.getPieceQuantity(), obj.getFrozenFlag(),obj.getEnterpriseNo(),obj.getEnterpriseName(),obj.getUserId());
			StorageItem storageItem = storageItemService.pickRegister(storageID, storehouseID, itemID, itemQuantity, costingAmount, pieceQuantity, frozenFlag, enterpriseNo, enterpriseName, userId);
		

			//3、更新批号管理数量（如果启用批号管理）出库追踪入库
			/*
			 * N:不需要批号管理
			 * W:仅需警告
			 * Y:需要不检查库存
			 * T:需要且检查库存
			 */
			if (Utils.isNotEmptyString(batchNo) && !"********************".equals(batchNo)){
				//storageItemBatchService.pickRegister(obj.getStorageID(), storehouseID, obj.getItemID(), obj.getBatchNo(), obj.getItemQuantity(), obj.getPieceQuantity(),obj.getEnterpriseNo(),obj.getEnterpriseName(),obj.getUserId());
				storageItemBatchService.pickRegister(storageID, storehouseID, itemID, batchNo, itemQuantity, costingAmount, pieceQuantity, enterpriseNo, enterpriseName, userId);
			}
			
			//启用项目库存管理
			if (Utils.isNotEmptyString(projectNo)){
				//是否产生项目库表还需论证
			}
			
			//是否更新主档
			//if(mainFlag==1) {
				///////////////////////////////////////////////////////////////////////
				
				//2、更新物料总账（公司级，如果是调拨类的单据，则不调用此函数）
				fileItemService.pickRegister(itemID, itemQuantity, costingAmount, pieceQuantity, frozenFlag);
				////////////////////////////////////////////////////////////////
				
				/*
				//登记上级物料（如果本级是SKU等级）
				String fParent = fileItem.getfParent();
				if(fParent!=null) {
					storageItemService.pickRegister(storageID, fParent, srd.getBatchNo(), accountQuantity, accountPieceQuantity,srd.getEnterpriseNo(),srd.getEnterpriseName(),srd.getUserId());
					fileItemService.pickRegister(fParent, accountQuantity, accountPieceQuantity);
				}
				*/

				//3、更新批号管理数量（如果启用批号管理）出库追踪入库
				/*
				 * N:不需要批号管理
				 * W:仅需警告
				 * Y:需要不检查库存
				 * T:需要且检查库存
				 */
				if (Utils.isNotEmptyString(batchNo) && !"********************".equals(batchNo)){
					itemBatchService.pickRegister(batchNo, batchDescribe, itemID, itemQuantity, pieceQuantity, enterpriseNo, enterpriseName);
				}
			//}
			
			///////////////////////////////////////////////////////////////////////////
			/*
			//TODO:（序列号管理--单件管理）
			String storeNo = srd.getStoreNo();
			if (storeNo!=null
					&& !srd.getStoreNo().equals("********************")
					&& !srd.getStoreNo().equals("")
					){
				//分解字符串
				String[] serialNumbers = storeNo.split(",");
				for(int i=0;i<serialNumbers.length;i++){
					String serialNumber = serialNumbers[i];
					if(serialNumber!=null && !"".equals(serialNumber)){
						ItemStore is = itemStoreService.getByNo(srd.getItemID(), serialNumber, srd.getEnterpriseNo());
						//判断序号是否存在，不存在则报错
						if(is!=null){
							//登记序列号移动轨迹
							String itemID = srd.getItemID();
							String originNo = srd.getRecordDetailNo();
							
							String enterpriseNo = srd.getEnterpriseNo();
							//删除序列号移动记录
							itemStoreDetailService.delete(serialNumber, itemID, originNo, enterpriseNo);
							
						}else{
							try {
								throw new Exception("序列号："+serialNumber+"档案不存在，请建立档案。");
							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					}
				}
//				ItemStoreUtil isu = new ItemStoreUtil();
//				ItemStore is = isu.getByNo(srd.getItemNo(), serialNumber, srd.getEnterpriseNo());
//				isu.pickRegister(srd.getStoreNo(), srd.getItemNo(), srd.getItemDescribe(),srd.getRationSize(), srd.getUnitCode(), srd.getUnitName(), srd.getBatchNo(), accountQuantity, accountPieceQuantity, srd.getAbcGrade(), srd.getOrderWeight(), srd.getOrderSize(),srd.getItemWeight(),srd.getItemSize(), srd.getEnterpriseNo(), srd.getEnterpriseName());
				//仓库序（列）号管理
//				StorageItemStoreUtil sisu = new StorageItemStoreUtil();
//				sisu.pickRegister(storageNo, storageName, srd.getItemNo(), srd.getItemDescribe(), srd.getRationSize(), srd.getUnitCode(), srd.getUnitName(), accountQuantity, accountPieceQuantity, floorNo, srd.getStoreNo(),srd.getBarCode(),srd.getBatchNo(), factoryNo,factoryName, srd.getEnterpriseNo(),srd.getEnterpriseName());

			}
			*/
			///////////////////////////////////////////////////////////////////////


			return storageItem;
		}
		
		return null;
	}

	//库存明细账过账
	@Transactional
	private StorageItem posting(StorageLedgerDetail storageLedgerDetail, String userId) {
		String revOpay = storageLedgerDetail.getRevOpay();
		
		String storageID = storageLedgerDetail.getStorageID();
		String itemID = storageLedgerDetail.getItemID();
		String batchNo = storageLedgerDetail.getBatchNo();
		String batchDescribe = storageLedgerDetail.getBatchDescribe();
		String storeNo = storageLedgerDetail.getStoreNo();
		String projectNo = storageLedgerDetail.getProjectNo();
		int frozenFlag = storageLedgerDetail.getFrozenFlag();
		String enterpriseNo = storageLedgerDetail.getEnterpriseNo();
		String enterpriseName = storageLedgerDetail.getEnterpriseName();
		
		BigDecimal itemQuantity = storageLedgerDetail.getItemQuantity();
		BigDecimal pieceQuantity = storageLedgerDetail.getPieceQuantity();
		BigDecimal costingAmount = storageLedgerDetail.getCostingAmount();
		
		int postedFlag = storageLedgerDetail.getPostedFlag(); //过账标识
		if(postedFlag==0) {
			//还未过账，过账
			
			//记账
			StorageItem storageItem = this.bookkeeping(revOpay, storageID, itemID, itemQuantity, pieceQuantity, costingAmount, batchNo, batchDescribe, storeNo, projectNo, frozenFlag, userId, enterpriseNo, enterpriseName);
			
			/////////////////////////////////////////////////////////////
			//仓库结存数量、金额、件数
			BigDecimal itemQuantityL = storageItem.getItemQuantityL();
			BigDecimal pieceQuantityL = storageItem.getPieceQuantityL();
			BigDecimal costingAmountL = storageItem.getCostingAmount();
			BigDecimal costingAmountPerL = BigDecimal.ZERO;
			//结存单位成本
			if(itemQuantityL.compareTo(BigDecimal.ZERO)!=0) {
				costingAmountPerL = costingAmountL.divide(itemQuantityL, 6, RoundingMode.HALF_UP);
			}
			///////////////////////////////////////////////////////////////////////
	
			storageLedgerDetail.setItemQuantityL(itemQuantityL);
			storageLedgerDetail.setPieceQuantityL(pieceQuantityL);
			storageLedgerDetail.setCostingAmountL(costingAmountL);
			storageLedgerDetail.setCostingAmountPerL(costingAmountPerL);
			
			storageLedgerDetail.setPostedFlag(1);
			//更新成本明细账
			storageLedgerDetailService.update(storageLedgerDetail);
			return storageItem;
		}
		if(postedFlag==1) {
			//已经过账，撤回
			
			//记账
			StorageItem storageItem = this.bookkeeping(revOpay, storageID, itemID, itemQuantity.negate(), pieceQuantity.negate(), costingAmount.negate(), batchNo, batchDescribe, storeNo, projectNo, frozenFlag, userId, enterpriseNo, enterpriseName);
			
			/////////////////////////////////////////////////////////////
			//仓库结存数量、金额、件数
			BigDecimal itemQuantityL = storageItem.getItemQuantityL();
			BigDecimal pieceQuantityL = storageItem.getPieceQuantityL();
			BigDecimal costingAmountL = storageItem.getCostingAmount();
			BigDecimal costingAmountPerL = BigDecimal.ZERO;
			//结存单位成本
			if(itemQuantityL.compareTo(BigDecimal.ZERO)!=0) {
				costingAmountPerL = costingAmountL.divide(itemQuantityL, 6, RoundingMode.HALF_UP);
			}
			///////////////////////////////////////////////////////////////////////
	
			storageLedgerDetail.setItemQuantityL(itemQuantityL);
			storageLedgerDetail.setPieceQuantityL(pieceQuantityL);
			storageLedgerDetail.setCostingAmountL(costingAmountL);
			storageLedgerDetail.setCostingAmountPerL(costingAmountPerL);
			
			storageLedgerDetail.setPostedFlag(0);
			//更新成本明细账
			storageLedgerDetailService.update(storageLedgerDetail);
			return storageItem;
		}
		
		return null;
	}

	//库存记账（审核）
	@Override
	@Transactional
	public int postingExt(			
			String recordNo 
			,String serialNo
			,String fMasterID
			
			,String systemCode 
			,String billType 
			,String billTypeName 
			,String revOpay 
			,String costingCode 
			,int dealType

			,Date orderDate 
			
			,String storageTypeD
			,String storageTypeDLabel
			,String providerID
			,String providerNo
			,String shortName
			,String providerName
			
			,String storageType
			,String storageTypeLabel
			,String storageID
			,String storageNo
			,String storageName
			,String floorNo
			//仓库ID
//			,String storehouseID

			,String itemID
			,String itemNo
			,String itemName
			,String itemProperty
			
			,String unitCode
			,String unitName
			
			,int validDays
			,int checkoutAgainDays
			
			,BigDecimal itemQuantity
			,BigDecimal pieceQuantity 

			,BigDecimal materialAmountPer 
			,BigDecimal workingAmountPer 
			,BigDecimal manufactAmountPer 
			,BigDecimal processAmountPer 
			,BigDecimal costingAmountPer

			,BigDecimal materialAmount 
			,BigDecimal workingAmount 
			,BigDecimal manufactAmount 
			,BigDecimal processAmount 
			,BigDecimal costingAmount 

			,String batchNo
			,String batchDescribe
			,Date produceDate 
			,Date validDate 
			,Date checkoutAgainDate 

			,String storeNo
			
			,String projectNo
			,String workNo
			
			,int frozenFlag

			,String userId 
			,String enterpriseNo 
			,String enterpriseName 
			) {
		
		
		//执行出入库
		if("I".equals(revOpay) || "O".equals(revOpay)) {
			//出入库
			
			//交易对象
			String tradeobjType = storageTypeD;
			String tradeobjTypeLabel = storageTypeDLabel;
			String tradeobjID = providerID;
			String tradeobjNo = providerNo;
			String tshortName = shortName;
			String tradeobjName = providerName;
			
//			String storageType = srd.getStorageType();
//			String storageTypeLabel = srd.getStorageTypeLabel();
//			String storageID = srd.getStorageID();
//			String storageNo = srd.getStorageNo();
//			String storageName = srd.getStorageName();
//			String floorNo = srd.getFloorNo();

			//登记成本明细账
			StorageLedgerDetail storageLedgerDetail = storageLedgerDetailService.insert(recordNo, serialNo, fMasterID, systemCode, billType, billTypeName, revOpay, costingCode, dealType, orderDate, tradeobjType, tradeobjTypeLabel, tradeobjID, tradeobjNo, tshortName, tradeobjName, storageType, storageTypeLabel, storageID, storageNo, storageName, floorNo, itemID, itemNo, itemName, itemProperty, unitCode, unitName, validDays, checkoutAgainDays, itemQuantity, pieceQuantity, materialAmountPer, workingAmountPer, manufactAmountPer, processAmountPer, costingAmountPer, materialAmount, workingAmount, manufactAmount, processAmount, costingAmount, batchNo, batchDescribe, produceDate, validDate, checkoutAgainDate, storeNo, projectNo, workNo, frozenFlag, userId, enterpriseNo, enterpriseName);
			if(storageLedgerDetail==null) {
				return -9;
			}
			//过账
			this.posting(storageLedgerDetail, userId);

		}else {
			//调拨
			
			//移出仓库
			revOpay = "O";
			
			//交易对象
			String tradeobjType = storageType;
			String tradeobjTypeLabel = storageTypeLabel;
			String tradeobjID = storageID;
			String tradeobjNo = storageNo;
			String tshortName = storageName;
			String tradeobjName = floorNo;

//			String providerID = srd.getProviderID();
//			String storageTypeD = srd.getStorageTypeD();
//			String storageTypeDLabel = srd.getStorageTypeDLabel();
//			String providerNo = srd.getProviderNo();
//			String shortName = srd.getShortName();
//			String providerName = srd.getProviderName();

			//登记成本明细账
			StorageLedgerDetail storageLedgerDetail = storageLedgerDetailService.insert(recordNo, serialNo, fMasterID, systemCode, billType, billTypeName, revOpay, costingCode, dealType, orderDate, tradeobjType, tradeobjTypeLabel, tradeobjID, tradeobjNo, tshortName, tradeobjName, storageTypeD, storageTypeDLabel, providerID, providerNo, shortName, providerName, itemID, itemNo, itemName, itemProperty, unitCode, unitName, validDays, checkoutAgainDays, itemQuantity, pieceQuantity, materialAmountPer, workingAmountPer, manufactAmountPer, processAmountPer, costingAmountPer, materialAmount, workingAmount, manufactAmount, processAmount, costingAmount, batchNo, batchDescribe, produceDate, validDate, checkoutAgainDate, storeNo, projectNo, workNo, frozenFlag, userId, enterpriseNo, enterpriseName);
			if(storageLedgerDetail==null) {
				return -9;
			}
			//过账
			this.posting(storageLedgerDetail, userId);
			
			
			//移入仓库
			revOpay = "I";
			
			//交易对象
			tradeobjType = storageTypeD;
			tradeobjTypeLabel = storageTypeDLabel;
			tradeobjID = providerID;
			tradeobjNo = providerNo;
			tshortName = shortName;
			tradeobjName = providerName;

//			String storageID = srd.getStorageID();
//			String storageType = srd.getStorageType();
//			String storageTypeLabel = srd.getStorageTypeLabel();
//			String storageNo = srd.getStorageNo();
//			String storageName = srd.getStorageName();
//			String floorNo = srd.getFloorNo();

			//登记成本明细账
			storageLedgerDetail = storageLedgerDetailService.insert(recordNo, serialNo, fMasterID, systemCode, billType, billTypeName, revOpay, costingCode, dealType, orderDate, tradeobjType, tradeobjTypeLabel, tradeobjID, tradeobjNo, tshortName, tradeobjName, storageType, storageTypeLabel, storageID, storageNo, storageName, floorNo, itemID, itemNo, itemName, itemProperty, unitCode, unitName, validDays, checkoutAgainDays, itemQuantity, pieceQuantity, materialAmountPer, workingAmountPer, manufactAmountPer, processAmountPer, costingAmountPer, materialAmount, workingAmount, manufactAmount, processAmount, costingAmount, batchNo, batchDescribe, produceDate, validDate, checkoutAgainDate, storeNo, projectNo, workNo, frozenFlag, userId, enterpriseNo, enterpriseName);
			if(storageLedgerDetail==null) {
				return -9;
			}
			//过账
			this.posting(storageLedgerDetail, userId);
			
		}

		
		
		return 0;
	}


	//库存反记账（撤销审核）
	@Transactional
	@Override
	public int unpostingExt(String recordNo, String serialNo, String revOpay, String userId, String enterpriseNo) {
		
//		String userId = srd.getUserId();
//		String revOpay = srd.getRevOpay();
//		String recordNo = srd.getRecordNo();
//		String serialNo = srd.getSerialNo();
//		String enterpriseNo = srd.getEnterpriseNo();
		
		//执行出入库
		if("I".equals(revOpay) || "O".equals(revOpay)) {
			//出入库
			
			//获取明细账
			StorageLedgerDetail storageLedgerDetail = storageLedgerDetailService.getByNo(recordNo, serialNo, revOpay, enterpriseNo);
			if(storageLedgerDetail==null) {
				return -9;
			}
			//过账
			this.posting(storageLedgerDetail, userId);
			//删除成本明细账
			storageLedgerDetailService.delete(storageLedgerDetail.getfID());

		}else {
			//调拨
			
			//移入仓库
			revOpay = "I";
			//获取明细账
			StorageLedgerDetail storageLedgerDetail = storageLedgerDetailService.getByNo(recordNo, serialNo, revOpay, enterpriseNo);
			if(storageLedgerDetail==null) {
				return -9;
			}
			//过账
			this.posting(storageLedgerDetail, userId);
			//删除成本明细账
			storageLedgerDetailService.delete(storageLedgerDetail.getfID());

			//移出仓库
			revOpay = "O";
			//获取明细账
			storageLedgerDetail = storageLedgerDetailService.getByNo(recordNo, serialNo, revOpay, enterpriseNo);
			if(storageLedgerDetail==null) {
				return -9;
			}
			//过账
			this.posting(storageLedgerDetail, userId);
			//删除成本明细账
			storageLedgerDetailService.delete(storageLedgerDetail.getfID());
		}
		
		return 0;
		
	}
	
	
	//提交（数据验证通过之后执行）
	@Transactional
	private int submitRelation(StorageRecordDetail obj){
		
		//TODO 退库处理
		if ((obj.getBillType().equals("JCGH") && obj.getOrigin().equals("JCDJ"))
				|| (obj.getBillType().equals("JRGH") && obj.getOrigin().equals("JRDJ"))
				|| (obj.getBillType().equals("XHCK") && obj.getOrigin().equals("BFDJ"))//特别：并非退库，作为报废单的销毁出库数量处理
				){
			storageRecordDetailService.updateBackItemQuantityIng(
						obj.getOriginNo()
						,obj.getOriginSerialNo()
						,obj.getOrigin()
						,obj.getEnterpriseNo()
						,obj.getItemAmount()
						,obj.getWasterAmount()
						,obj.getUllageAmount()
						,obj.getArriveAmountBack()
						);
		}
		
		//TODO 报废处理
		
		
		return 0;
	}

	//撤回
	@Transactional
	private int recallRelation(StorageRecordDetail obj){

		//TODO 退库处理
		if ((obj.getBillType().equals("JCGH") && obj.getOrigin().equals("JCDJ"))
				|| (obj.getBillType().equals("JRGH") && obj.getOrigin().equals("JRDJ"))
				|| (obj.getBillType().equals("XHCK") && obj.getOrigin().equals("BFDJ"))//特别：并非退库，作为报废单的销毁出库数量处理
				){
			storageRecordDetailService.updateBackItemQuantityIng(
						obj.getOriginNo()
						,obj.getOriginSerialNo()
						,obj.getOrigin()
						,obj.getEnterpriseNo()
						,obj.getItemAmount().negate()
						,obj.getWasterAmount().negate()
						,obj.getUllageAmount().negate()
						,obj.getArriveAmountBack().negate()
						);
		}
		
		//TODO 报废处理
		
		return 0;
	}

	@Transactional
	private int doItStorage(StorageRecordDetail srd, String userId) {
		// TODO Auto-generated method stub
//		System.out.println("doIt.billType-->"+srd.getBillType());
//		System.out.println("doIt.getAccountQuantityI-->"+srd.getAccountQuantityI());
//		System.out.println("doIt.getAccountQuantityO-->"+accountQuantity);
		
		//调用入库类，提交单据
		
		FileItem fileItem = fileItemService.getByID(srd.getItemID());
		if(fileItem==null){
			return -1;
		}
		
//		if(fileItem.getCheckin()==0) {
//			//无需出入库登记
//			return 0;
//		}
		
		//系统参数设置
		ParamSetting paramSetting = paramSettingService.getByNo(srd.getEnterpriseNo());
		//采用成本制度【0：标准成本制，1：实际成本制】
		int costingRules = 1;
		//实际成本制：1、移动加权平均，2、月末加权平均，3、先进先出，4、个别计价（分批认定）
		int costingType = 1;
		if(paramSetting!=null) {
			costingRules = paramSetting.getCostingRules();
			costingType = paramSetting.getCostingType();
		}
		
		/*
		$scope.dataCostingType = [
		              			{"costingType":1,"costingTypeLabel":"1:移动加权平均"}
		              			,{"costingType":2,"costingTypeLabel":"2:月末一次加权加权平均"}
								,{"costingType":3,"costingTypeLabel":"3:先进先出X"}
								,{"costingType":4,"costingTypeLabel":"4:个别计价（分批认定）X"}
		              			];
		*/
		//成本计价方式
//		int costingType = paramSetting.getCostingType();
		
		//成本计价方式
//		int costingType = fileItem.getCostingType();
//		System.out.println("成本计价方式costingType-->>"+costingType);
		
		/*
		//1：入库，2：销货，3：领用，4：调拨，5：调整。
		int dealType = 0;
		//影响成本码
		String costingCode = null;
		
		String billType = srd.getBillType();
		String enterpriseNo = srd.getEnterpriseNo();
		BillSettingOrg billSettingOrg = billSettingOrgService.getByNo(billType, enterpriseNo);
		if(billSettingOrg!=null) {
			dealType = billSettingOrg.getDealType();
			costingCode = billSettingOrg.getCostingCode();
		}else {
			BillSetting billSetting = billSettingService.getByNo(billType);
			if(billSetting==null) {
				return -99;
			}else {
				dealType = billSetting.getDealType();
				costingCode = billSetting.getCostingCode();
			}
		}
		*/

		String itemID = srd.getItemID();
		String revOpay = srd.getRevOpay();

		//数量（账）
		BigDecimal accountQuantity = srd.getItemAmount().multiply(new BigDecimal(srd.getDirection())).setScale(2, RoundingMode.HALF_UP);
		//件数（账）
		BigDecimal accountPieceQuantity = srd.getPieceQuantity().multiply(new BigDecimal(srd.getDirection())).setScale(2, RoundingMode.HALF_UP);
		
		//////////登记明细账是公用参数
		BigDecimal itemQuantity = accountQuantity;
		BigDecimal pieceQuantity = accountPieceQuantity;
		String batchNo = srd.getBatchNo();
		String batchDescribe = srd.getBatchDescribe();

		String storeNo = srd.getStoreNo();
		String projectNo = srd.getProjectNo();
		
		int frozenFlag = srd.getFrozenFlag();

		String enterpriseNo = srd.getEnterpriseNo();
		String enterpriseName = srd.getEnterpriseName();
		
		String recordNo = srd.getRecordNo();
		String serialNo = srd.getSerialNo();
		String fMasterID = srd.getfMasterID();
		
		String systemCode = srd.getSystemCode();
		String billType = srd.getBillType();
		String billTypeName = srd.getBillTypeName();
		int dealType = srd.getDealType();
		String costingCode = srd.getCostingCode();

		Date orderDate = srd.getOrderDate();

		String itemNo = srd.getItemNo();
		String itemName = srd.getItemName();
		String itemProperty = srd.getItemProperty();
		
		String unitCode = srd.getUnitCode();
		String unitName = srd.getUnitName();
		
		int validDays = srd.getValidDays();
		int checkoutAgainDays = srd.getCheckoutAgainDays();

		Date produceDate = srd.getProduceDate();
		Date validDate = srd.getValidDate();
		Date checkoutAgainDate = srd.getCheckoutAgainDate();
		String workNo = srd.getWorkNo();
		
		String storageTypeD = srd.getStorageTypeD();
		String storageTypeDLabel = srd.getStorageTypeDLabel();
		String providerID = srd.getProviderID();
		String providerNo = srd.getProviderNo();
		String shortName = srd.getShortName();
		String providerName = srd.getProviderName();
		
		String storageType = srd.getStorageType();
		String storageTypeLabel = srd.getStorageTypeLabel();
		String storageID = srd.getStorageID();
		String storageNo = srd.getStorageNo();
		String storageName = srd.getStorageName();
		String floorNo = srd.getFloorNo();
		//////////////////////////////////////////////
		
		
		////////////////入库金额（账）/////////////////////////////
		//入账单位成本
		BigDecimal materialAmountPer = BigDecimal.ZERO;
		BigDecimal workingAmountPer = BigDecimal.ZERO;
		BigDecimal manufactAmountPer = BigDecimal.ZERO;
		BigDecimal processAmountPer = BigDecimal.ZERO;
		BigDecimal costingAmountPer = BigDecimal.ZERO;
		
		//标准成本制
		if(costingRules==0) {
			materialAmountPer = fileItem.getMaterialStandardPer();
			workingAmountPer = fileItem.getWorkingStandardPer();
			manufactAmountPer = fileItem.getManufactStandardPer();
			processAmountPer = fileItem.getProcessStandardPer();
			costingAmountPer = materialAmountPer.add(workingAmountPer).add(manufactAmountPer).add(processAmountPer);
		}
		
		BigDecimal materialAmount = BigDecimal.ZERO;
		BigDecimal workingAmount = BigDecimal.ZERO;
		BigDecimal manufactAmount = BigDecimal.ZERO;
		BigDecimal processAmount = BigDecimal.ZERO;
		BigDecimal costingAmount = BigDecimal.ZERO;
		

		//TODO:一、处理入库
		//TODO 入库单/////////////////////////////////////////////////////////////////////////
		///////////////////////////////////////////////////////////////////////
		//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>采购进货单（CGRK）
		///////////////////////////////////////////////////////////////////////

		if (srd.getBillType().equals("QTRK")
//			|| srd.getBillType().equals("CBKZ")
//			|| srd.getBillType().equals("CBTZ")
		){
			//int mainFlag = 1; //是否更新物料档案: 0:不更新,1:更新.

			////////////////入库金额（账）/////////////////////////////
			
			//实际成本制：1、移动加权平均，2、月末加权平均，3、先进先出，4、个别计价（分批认定）
			if(costingRules==1) {
				switch(costingType) {
					case 1://1、移动加权平均
						if(srd.getBillType().equals("QTRK")) {
							//采购进货单或者退货单
							//单位成本使用实际单位成本：（未税金额 - 扣款金额）/入库数量
							if(accountQuantity.compareTo(BigDecimal.ZERO)!=0){
								materialAmountPer = (srd.getOrderAmountOld().subtract(srd.getDiscountAmount())).divide(accountQuantity, 6, RoundingMode.HALF_UP);
							}
							workingAmountPer = BigDecimal.ZERO;
							manufactAmountPer = BigDecimal.ZERO;
							processAmountPer = BigDecimal.ZERO;
							costingAmountPer = materialAmountPer.add(workingAmountPer).add(manufactAmountPer).add(processAmountPer);
						}
						break;
					case 2://2、月末加权平均
						
						break;
					case 3://3、先进先出
						
						break;
					case 4://4、个别计价（分批认定）
						
						break;
					default:
						System.out.println("未知存货计价方式！");
				}
			}
			
			//金额
			materialAmount = materialAmountPer.multiply(accountQuantity).setScale(2,BigDecimal.ROUND_HALF_UP);
			workingAmount = workingAmountPer.multiply(accountQuantity).setScale(2,BigDecimal.ROUND_HALF_UP);
			manufactAmount = manufactAmountPer.multiply(accountQuantity).setScale(2,BigDecimal.ROUND_HALF_UP);
			processAmount = processAmountPer.multiply(accountQuantity).setScale(2,BigDecimal.ROUND_HALF_UP);
			costingAmount = materialAmount.add(workingAmount).add(manufactAmount).add(processAmount);
			
			//////////////////////////////////////////////////////////
		}
		

		//TODO:二、处理出库
		/////////////////////////////////////////////////////////////////////////////////
		/////////////////(转出仓库：providerNo，转入仓库：storageNo)//////////////////////
		/////////////////////////////////////////////////////////////////////////////////
		//TODO 出库单/////////////////////////////////////////////////////////////////////////
		///////////////////////////////////////////////////////////////////////
		//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<销售发货单（XSCK）
		///////////////////////////////////////////////////////////////////////
		if (srd.getBillType().equals("QTCK") || srd.getBillType().equals("XHCK")
			){
			
			//int mainFlag = 1; //是否更新物料档案: 0:不更新,1:更新.
			//String storageID = srd.getStorageID();

			////////////////出库金额（账）/////////////////////////////
			
			//实际成本制：1、移动加权平均，2、月末加权平均，3、先进先出，4、个别计价（分批认定）
			if(costingRules==1) {
				switch(costingType) {
					case 1://1、移动加权平均
						//其他类型出库单据，其他出库单
						//成本由前端单据录入，无需在此处处理
						//单位成本使用实际单位成本：（未税金额 - 扣款金额）/入库数量
						if(accountQuantity.compareTo(BigDecimal.ZERO)!=0){
							materialAmountPer = (srd.getOrderAmountOld().subtract(srd.getDiscountAmount())).divide(accountQuantity, 6, RoundingMode.HALF_UP);
						}
						workingAmountPer = BigDecimal.ZERO;
						manufactAmountPer = BigDecimal.ZERO;
						processAmountPer = BigDecimal.ZERO;
						costingAmountPer = materialAmountPer.add(workingAmountPer).add(manufactAmountPer).add(processAmountPer);
						break;
					case 2://2、月末加权平均
						
						break;
					case 3://3、先进先出
						
						break;
					case 4://4、个别计价（分批认定）
						
						break;
					default:
						System.out.println("未知存货计价方式！");
				}
			}
			
			//金额
			materialAmount = materialAmountPer.multiply(accountQuantity).setScale(2,BigDecimal.ROUND_HALF_UP);
			workingAmount = workingAmountPer.multiply(accountQuantity).setScale(2,BigDecimal.ROUND_HALF_UP);
			manufactAmount = manufactAmountPer.multiply(accountQuantity).setScale(2,BigDecimal.ROUND_HALF_UP);
			processAmount = processAmountPer.multiply(accountQuantity).setScale(2,BigDecimal.ROUND_HALF_UP);
			costingAmount = materialAmount.add(workingAmount).add(manufactAmount).add(processAmount);
			
			//////////////////////////////////////////////////////////
		
		}
		
		//三、单独处理调拨单和报废单
		if (srd.getBillType().equals("DBDJ") //调拨单
				|| (srd.getBillType().equals("BFDJ") && "ITEM".equals(srd.getOrigin()))//报废单据
				|| srd.getBillType().equals("JRDJ")//借入单据
				|| srd.getBillType().equals("JRGH")//借入归还单据
				|| srd.getBillType().equals("JCDJ")//借出单据
				|| srd.getBillType().equals("JCGH")//借出归还单据
				){
			
			//int mainFlag = 0; //是否更新物料档案: 0:不更新,1:更新.
			//移出仓库
			//String providerID = srd.getProviderID();
			
			////////////////出入库金额（账）/////////////////////////////
			
			//实际成本制：1、移动加权平均，2、月末加权平均，3、先进先出，4、个别计价（分批认定）
			if(costingRules==1) {
				switch(costingType) {
					case 1://1、移动加权平均
						if(srd.getBillType().equals("JRDJ")//借入单据
							|| srd.getBillType().equals("JRGH")//借入归还单据
							|| srd.getBillType().equals("JCDJ")//借出单据
							|| srd.getBillType().equals("JCGH")//借出归还单据
							){
							//销货单或者退货单
							//单位成本使用实际单位成本：物料仓库档案中的实际单位成本
							//出库时：物料仓库档案的出库成本与物料档案的出库单位成本不同，但是出库成本相同。
							StorageItem storageItem = storageItemService.getByNo(providerID, srd.getItemID());
							if(storageItem!=null) {
								if(storageItem.getItemQuantityL().compareTo(BigDecimal.ZERO)!=0) {
									materialAmountPer = storageItem.getCostingAmount().divide(storageItem.getItemQuantityL(), 6, RoundingMode.HALF_UP);
								}
							}
							workingAmountPer = BigDecimal.ZERO;
							manufactAmountPer = BigDecimal.ZERO;
							processAmountPer = BigDecimal.ZERO;
							costingAmountPer = materialAmountPer.add(workingAmountPer).add(manufactAmountPer).add(processAmountPer);
						}else {
							//其他类型出库单据，其他出库单
							//成本由前端单据录入，无需在此处处理
							//单位成本使用实际单位成本：（未税金额 - 扣款金额）/入库数量
							if(accountQuantity.compareTo(BigDecimal.ZERO)!=0){
								materialAmountPer = srd.getOrderAmountOld().divide(accountQuantity, 6, RoundingMode.HALF_UP);
							}
							workingAmountPer = BigDecimal.ZERO;
							manufactAmountPer = BigDecimal.ZERO;
							processAmountPer = BigDecimal.ZERO;
							costingAmountPer = materialAmountPer.add(workingAmountPer).add(manufactAmountPer).add(processAmountPer);
						}
						break;
					case 2://2、月末加权平均
						
						break;
					case 3://3、先进先出
						
						break;
					case 4://4、个别计价（分批认定）
						
						break;
					default:
						System.out.println("未知存货计价方式！");
				}
			}
			
			
			//金额
			materialAmount = materialAmountPer.multiply(accountQuantity).setScale(2,BigDecimal.ROUND_HALF_UP);
			workingAmount = workingAmountPer.multiply(accountQuantity).setScale(2,BigDecimal.ROUND_HALF_UP);
			manufactAmount = manufactAmountPer.multiply(accountQuantity).setScale(2,BigDecimal.ROUND_HALF_UP);
			processAmount = processAmountPer.multiply(accountQuantity).setScale(2,BigDecimal.ROUND_HALF_UP);
			costingAmount = materialAmount.add(workingAmount).add(manufactAmount).add(processAmount);
			//////////////////////////////////////////////////////////

		}
		
		//库存记账（审核）
		this.postingExt(recordNo, serialNo, fMasterID, systemCode, billType, billTypeName, revOpay, costingCode, dealType, orderDate, storageTypeD, storageTypeDLabel, providerID, providerNo, shortName, providerName, storageType, storageTypeLabel, storageID, storageNo, storageName, floorNo, itemID, itemNo, itemName, itemProperty, unitCode, unitName, validDays, checkoutAgainDays, itemQuantity, pieceQuantity, materialAmountPer, workingAmountPer, manufactAmountPer, processAmountPer, costingAmountPer, materialAmount, workingAmount, manufactAmount, processAmount, costingAmount, batchNo, batchDescribe, produceDate, validDate, checkoutAgainDate, storeNo, projectNo, workNo, frozenFlag, userId, enterpriseNo, enterpriseName);
		
		return 0;
	}

	@Transactional
	private int unDoStorage(StorageRecordDetail srd, String userId) {
		
		String revOpay = srd.getRevOpay();
		String recordNo = srd.getRecordNo();
		String serialNo = srd.getSerialNo();
		String enterpriseNo = srd.getEnterpriseNo();
		//库存反记账（撤销审核）
		this.unpostingExt(recordNo, serialNo, revOpay, userId, enterpriseNo);
		
		return 0;
	}

	
	@Transactional
	private int doItRelation(StorageRecordDetail srd){

		//TODO：八、处理关联单据

		//TODO 五、退库处理
		if ((srd.getBillType().equals("JCGH") && srd.getOrigin().equals("JCDJ"))
				|| (srd.getBillType().equals("JRGH") && srd.getOrigin().equals("JRDJ"))
				|| (srd.getBillType().equals("XHCK") && srd.getOrigin().equals("BFDJ"))//特别：并非退库，作为报废单的销毁出库数量处理

				){
			
				if(srd.getOrigin()!=null && srd.getOriginNo()!=null){

					storageRecordDetailService.updateBackItemQuantity(
							srd.getOriginNo()
							,srd.getOriginSerialNo()
							,srd.getOrigin()
							,srd.getEnterpriseNo()
							,srd.getItemAmount()
							,srd.getWasterAmount()
							,srd.getUllageAmount()
							,srd.getArriveAmountBack()
							,srd.getPieceQuantity()
							);
					
				}
				
				//TODO：处理退库单关联单据（订单）

			}	
		
		//TODO 六、报废处理（报废单关联单据处理）


		
		return 0;
	}

	@Transactional
	private int unDoRelation(StorageRecordDetail srd){

		//TODO：八、处理相关单据
		
		//TODO 五、退库处理
		if ((srd.getBillType().equals("JCGH") && srd.getOrigin().equals("JCDJ"))
				|| (srd.getBillType().equals("JRGH") && srd.getOrigin().equals("JRDJ"))
				|| (srd.getBillType().equals("XHCK") && srd.getOrigin().equals("BFDJ"))//特别：并非退库，作为报废单的销毁出库数量处理
				){
			if(srd.getOrigin()!=null && srd.getOriginNo()!=null){
				
			storageRecordDetailService.updateBackItemQuantity(
						srd.getOriginNo()
						,srd.getOriginSerialNo()
						,srd.getOrigin()
						,srd.getEnterpriseNo()
						,srd.getItemAmount().negate()
						,srd.getWasterAmount().negate()
						,srd.getUllageAmount().negate()
						,srd.getArriveAmountBack().negate()
						,srd.getPieceQuantity().negate()
						);
				
			}
			//TODO：处理退库单关联单据（订单）
			
		}
		
		//TODO 六、报废处理（报废单关联单据处理）

		
		return 0;
	}

	
	////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////
	

	
	

	
	//提交出入库单
	@Override
	@Transactional
	public Map<String,Object> storageRecordConfirm(String rowID, String cUsercode, String cUsername, String userId, String employeeNo, String employeeName){
		
		StorageRecord obj = storageRecordService.getByID(rowID);
		
		MapMessage mapMessage = new MapMessage(obj.getfID(),obj.getRecordNo(),obj.getBillType(),obj.getBillTypeName()
				,MapMessage.STATUSINFO_SUCCESS_CODE//"http://www.iune.cn"
				,MapMessage.STATUSINFO_SUCCESS_MSG//"操作成功！"
				,MapMessage.STATUSINFO_SUCCESS_INFO//"操作成功！"
				,MapMessage.STATUSINFO_SUCCESS_FLAG//"success"
				);
		
		if("confirm".equals(obj.getAudit())){
			return mapMessage.toMap();
		}
		
		//验证数据完整性和有效性（同时可以验证库存是否不足）
		
		List<StorageRecordDetail> srds = storageRecordDetailService.getByMasterID(rowID);
		for(StorageRecordDetail srd:srds){
			//仓库数据有效性验证
			if("QTRK".equals(obj.getBillType()) || "QTCK".equals(obj.getBillType()) 
					|| "CBKZ".equals(obj.getBillType()) || "DBDJ".equals(obj.getBillType()) 
					) {
				String storageID = srd.getStorageID();
				FileStorage fileStorage = fileStorageService.getByID(storageID);
				if(fileStorage.getNodeKind()==null) {
					//不是末端仓库数据，不合法
					mapMessage.setStatusCode("100001");
					mapMessage.setStatusMsg(MapMessage.STATUSINFO_FAILURE_MSG);
					mapMessage.setStatusInfo("库存地不存在，无法撤销提交！");
					mapMessage.setStatusFlag(MapMessage.STATUSINFO_FAILURE_FLAG);
					return mapMessage.toMap();
				}
			}
		}

		//执行的相关联的单据更新
		for(StorageRecordDetail srd:srds){
			this.submitRelation(srd);
		}

		storageRecordDetailService.confirmByMasterID(rowID);
		
		//然后审核主表
		storageRecordService.confirm(rowID);
		
		//自动审核
		if(obj.getFlowType()==0){
			Map<String,Object> map = this.storageRecordAgreeIt(rowID, cUsercode, cUsername, userId, employeeNo, employeeName);
			mapMessage.fromMap(map);
		}
		
		return mapMessage.toMap();
	}
	
	//撤回出入库单
	@Override
	@Transactional
	public Map<String,Object> storageRecordActive(String rowID, String cUsercode, String cUsername, String userId, String employeeNo, String employeeName){
		StorageRecord obj = storageRecordService.getByID(rowID);
		
		MapMessage mapMessage = new MapMessage(obj.getfID(),obj.getRecordNo(),obj.getBillType(),obj.getBillTypeName()
				,MapMessage.STATUSINFO_SUCCESS_CODE//"http://www.iune.cn"
				,MapMessage.STATUSINFO_SUCCESS_MSG//"操作成功！"
				,MapMessage.STATUSINFO_SUCCESS_INFO//"操作成功！"
				,MapMessage.STATUSINFO_SUCCESS_FLAG//"success"
				);

		List<StorageRecordDetail> srds = storageRecordDetailService.getByMasterID(rowID);
//		for(StorageRecordDetail srd:srds){
//			//判断是否已经开具检验单
//		}
		

		//执行的相关联的单据更新
		for(StorageRecordDetail srd:srds){
			this.recallRelation(srd);
		}

		//首先审核从表
		storageRecordDetailService.activeByMasterID(rowID);
		
		//然后审核主表
		storageRecordService.active(rowID);
		
		return mapMessage.toMap();
	}
	
	//审核出入库单（改造为主从表不关联审核）
	@Override
	@Transactional
	public Map<String,Object> storageRecordAgreeIt(String rowID,String cUsercode,String cUsername, String userId, String employeeNo, String employeeName){
		
		StorageRecord sr = storageRecordService.getByID(rowID);

		MapMessage mapMessage = new MapMessage(sr.getfID(),sr.getRecordNo(),sr.getBillType(),sr.getBillTypeName()
				,MapMessage.STATUSINFO_SUCCESS_CODE//"http://www.iune.cn"
				,MapMessage.STATUSINFO_SUCCESS_MSG//"操作成功！"
				,MapMessage.STATUSINFO_SUCCESS_INFO//"操作成功！"
				,MapMessage.STATUSINFO_SUCCESS_FLAG//"success"
				);
		
		//判断检验状态
		
		List<StorageRecordDetail> srds = storageRecordDetailService.getByMasterID(rowID);
		//判断批号是否存在，判断库存为负控制
		
		
		//判断检验状态
		/*
		检验单
		检验方式
		0:免检
		1:抽检（减量）
		2:抽检（正常）
		3:抽检（加严）
		4:全检
		 */
		//var qualityType = dataDetail.getValue('qualityType',rowID);
		/*
		入库单	检验单
		检验状态	判定
		1:待验	
		2:合格	2:允收
		3:不良	3:拒收
		4:特采	4:特采
			
		9:在验	9:在验
		 */
		//var qualityStatus = dataDetail.getValue('qualityStatus',rowID);
		
		//然后检查子表
		for(StorageRecordDetail srd : srds){
			//判断库存是否可以为负数
			//判断是否库存量充足
			//检测范围：销售发货单，发料单，采购、委外、生产、工艺入库退回单
			if(srd.getBillType().equals("QTCK")){
				if("no".equals(srd.getProcedureStep())) {
					//不允许
					BigDecimal quantityL = BigDecimal.ZERO;
					StorageItem si = storageItemService.getByNo(srd.getStorageID(), srd.getItemID());
					if(si==null){
						quantityL = new BigDecimal(0);
					}else{
						quantityL = si.getItemQuantityL();
					}
					
					if (quantityL.compareTo(srd.getItemAmount())<0){
						//库存数量小于零
						mapMessage.setStatusCode("100003");
						mapMessage.setStatusMsg(MapMessage.STATUSINFO_FAILURE_MSG);
						mapMessage.setStatusInfo("单据存在库存不足项目，无法审核！");
						mapMessage.setStatusFlag(MapMessage.STATUSINFO_FAILURE_FLAG);
						return mapMessage.toMap();
					}
				}
			}
			//检测范围：调拨单
			if(srd.getBillType().equals("DBDJ") || srd.getBillType().equals("JCDJ") || srd.getBillType().equals("JCGH") || srd.getBillType().equals("JRDJ") || srd.getBillType().equals("JRGH")){
				if("no".equals(srd.getProcedureStepD())) {
					//不允许
					BigDecimal quantityL = BigDecimal.ZERO;
					StorageItem si = storageItemService.getByNo(srd.getProviderID(), srd.getItemID());
					if(si==null){
						quantityL = new BigDecimal(0);
					}else{
						quantityL = si.getItemQuantityL();
					}
					
					if (quantityL.compareTo(srd.getItemAmount())<0){
						//库存数量小于零
						mapMessage.setStatusCode("100003");
						mapMessage.setStatusMsg(MapMessage.STATUSINFO_FAILURE_MSG);
						mapMessage.setStatusInfo("单据存在库存不足项目，无法审核！");
						mapMessage.setStatusFlag(MapMessage.STATUSINFO_FAILURE_FLAG);
						return mapMessage.toMap();
					}
				}
			}
		}
		

		//首先审核从表
//		storageRecordDetailService.agreeItByMasterID(rowID);
		for(StorageRecordDetail srd : srds){
			
			srd.setAudit("confirm");
			srd.setConfirmDate(Utils.getCurrentDate());
			
			srd.setResultStatus("已审核");
//			dao.update(srd);
			//执行更新操作
			if(srd.getCheckin()==1) {
				//需要出入库登记
				this.doItStorage(srd, userId);//库存数量更新
			}
			
			this.doItRelation(srd);//关联单据更新
		}
		
		//然后审核主表
		storageRecordService.agreeIt(rowID, cUsercode, cUsername, userId);

//		Map<String,Object> map = mapMessage.toMap();
		
		return mapMessage.toMap();

	}
	
	//反审核出入库单
	@Override
	@Transactional
	public Map<String,Object> storageRecordUnAgree(String rowID, String cUsercode, String cUsername, String userId, String employeeNo, String employeeName){
		//判断是否可以撤销
		
		StorageRecord sr = storageRecordService.getByID(rowID);
		MapMessage mapMessage = new MapMessage(sr.getfID(),sr.getRecordNo(),sr.getBillType(),sr.getBillTypeName()
				,MapMessage.STATUSINFO_SUCCESS_CODE//"http://www.iune.cn"
				,MapMessage.STATUSINFO_SUCCESS_MSG//"操作成功！"
				,MapMessage.STATUSINFO_SUCCESS_INFO//"操作成功！"
				,MapMessage.STATUSINFO_SUCCESS_FLAG//"success"
				);

		
		List<StorageRecordDetail> srds = storageRecordDetailService.getByMasterID(rowID);
		//然后检查子表
//		for(StorageRecordDetail srd : srds){
//			
//		}
	
//		storageRecordDetailService.unAgreeByMasterID(rowID);
		for(StorageRecordDetail srd : srds){

			srd.setAudit("active");
			srd.setConfirmDate(null);
			
			srd.setResultStatus("审核中");
//			dao.update(srd);
			//执行更新操作
			if(srd.getCheckin()==1) {
				//需要出入库登记
				this.unDoStorage(srd, userId);//库存数量更新
			}
			
			this.unDoRelation(srd);//关联单据更新
		}
		
		//然后审核主表
		storageRecordService.unAgree(rowID);
		
		return mapMessage.toMap();

	}
	

	//关闭出入库单
	@Override
	@Transactional
	public Map<String,Object> storageRecordClose(String rowID, String cUsercode, String cUsername, String userId, String employeeNo, String employeeName){
		StorageRecord obj = storageRecordService.getByID(rowID);
		
		MapMessage mapMessage = new MapMessage(obj.getfID(),obj.getRecordNo(),obj.getBillType(),obj.getBillTypeName()
				,MapMessage.STATUSINFO_SUCCESS_CODE//"http://www.iune.cn"
				,MapMessage.STATUSINFO_SUCCESS_MSG//"操作成功！"
				,MapMessage.STATUSINFO_SUCCESS_INFO//"操作成功！"
				,MapMessage.STATUSINFO_SUCCESS_FLAG//"success"
				);

		//首先审核从表
//		StorageRecordDetailUtil srdu = new StorageRecordDetailUtil();
		int rtn = storageRecordDetailService.closeByMasterID(rowID);
		if (rtn != 0){
			mapMessage.setStatusCode(MapMessage.STATUSINFO_FAILURE_CODE);
			mapMessage.setStatusMsg(MapMessage.STATUSINFO_FAILURE_MSG);
			mapMessage.setStatusInfo(MapMessage.STATUSINFO_FAILURE_INFO);
			mapMessage.setStatusFlag(MapMessage.STATUSINFO_FAILURE_FLAG);
			return mapMessage.toMap();
		}
		
		//然后审核主表
//		StorageRecordUtil sru = new StorageRecordUtil();
		rtn = storageRecordService.close(rowID);
		if (rtn != 0){
			mapMessage.setStatusCode(MapMessage.STATUSINFO_FAILURE_CODE);
			mapMessage.setStatusMsg(MapMessage.STATUSINFO_FAILURE_MSG);
			mapMessage.setStatusInfo(MapMessage.STATUSINFO_FAILURE_INFO);
			mapMessage.setStatusFlag(MapMessage.STATUSINFO_FAILURE_FLAG);
			return mapMessage.toMap();
		}
		
		return mapMessage.toMap();
	}

	//打开出入库单
	@Override
	@Transactional
	public Map<String,Object> storageRecordOpen(String rowID, String cUsercode, String cUsername, String userId, String employeeNo, String employeeName){
		StorageRecord obj = storageRecordService.getByID(rowID);
		
		MapMessage mapMessage = new MapMessage(obj.getfID(),obj.getRecordNo(),obj.getBillType(),obj.getBillTypeName()
				,MapMessage.STATUSINFO_SUCCESS_CODE//"http://www.iune.cn"
				,MapMessage.STATUSINFO_SUCCESS_MSG//"操作成功！"
				,MapMessage.STATUSINFO_SUCCESS_INFO//"操作成功！"
				,MapMessage.STATUSINFO_SUCCESS_FLAG//"success"
				);

		//首先审核从表
//		StorageRecordDetailUtil srdu = new StorageRecordDetailUtil();
		int rtn = storageRecordDetailService.openByMasterID(rowID);
		if (rtn != 0){
			mapMessage.setStatusCode(MapMessage.STATUSINFO_FAILURE_CODE);
			mapMessage.setStatusMsg(MapMessage.STATUSINFO_FAILURE_MSG);
			mapMessage.setStatusInfo(MapMessage.STATUSINFO_FAILURE_INFO);
			mapMessage.setStatusFlag(MapMessage.STATUSINFO_FAILURE_FLAG);
			return mapMessage.toMap();
		}
		
		//然后审核主表
//		StorageRecordUtil sru = new StorageRecordUtil();
		rtn = storageRecordService.open(rowID);
		if (rtn != 0){
			mapMessage.setStatusCode(MapMessage.STATUSINFO_FAILURE_CODE);
			mapMessage.setStatusMsg(MapMessage.STATUSINFO_FAILURE_MSG);
			mapMessage.setStatusInfo(MapMessage.STATUSINFO_FAILURE_INFO);
			mapMessage.setStatusFlag(MapMessage.STATUSINFO_FAILURE_FLAG);
			return mapMessage.toMap();
		}
		
		return mapMessage.toMap();
	}
	

	
	//调拨单/报废单打印
	@Override
	public void invDBDJPrintPDF(String fID, Document doc) throws Exception {
		
//	@Test
//	public void storageRecordPrintPDF() throws Exception {
//		System.out.println("fID-->"+id);
		
//	    Document doc = new Document();// 创建一个PDF文档，我们的PDF内容都写在上面
	    
//	    PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(new File("c://pdftest//storageRecord.pdf"))); // 将pdf文档写入文件

//		String fID = "bf61ec2bc8163a3ad3d8572ad2fee7c6";
		StorageRecord storageRecord = storageRecordService.getByID(fID);
	   
//	    response.setContentType("application/pdf");
//	    PdfWriter.getInstance(doc, response.getOutputStream());
//	    
//	    doc.open();
	    
	    Font fontEN = new Font(BaseFont.createFont(),9);
	    BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);  	    
//	    Font font = new Font(baseFont, 10, Font.ITALIC);
	    Font fontCN = new Font(baseFont, 9);
	    Paragraph pEnterpriseName = new Paragraph(storageRecord.getEnterpriseName(),fontCN);
	    // 居中显示
	    pEnterpriseName.setAlignment(Element.ALIGN_CENTER);
	    pEnterpriseName.setSpacingAfter(-10);
	    Paragraph pBillTypeName = new Paragraph(storageRecord.getBillTypeName(),new Font(baseFont,20));
	    // 居中显示
	    pBillTypeName.setAlignment(Element.ALIGN_CENTER);
	    LineSeparator line = new LineSeparator(1f, 100, BaseColor.BLACK, Element.ALIGN_CENTER, -5f);

	    
	    
	    
	    
	    
	    doc.add(pEnterpriseName);
	    doc.add(pBillTypeName);
	    doc.add(line);
	    
	    
        PdfPTable masterHead = new PdfPTable(8);
        
//        masterHead.setTotalWidth(new float[]{60, 200, 60, 200});
        masterHead.setTotalWidth(new float[]{45, 85, 45, 85, 45, 85, 45, 85});
        masterHead.setLockedWidth(true);
        masterHead.setSpacingBefore(10);
        
        PdfPCell ordrDateCell = new PdfPCell(new Phrase("单据日期:", fontCN));
        ordrDateCell.setUseBorderPadding(true);
        //
        // Setting cell's border width and color
        //
        ordrDateCell.setBorderWidth(0f);
//        ordrDateCell.setBorderColor(BaseColor.BLUE);
        masterHead.addCell(ordrDateCell);

        PdfPCell ordrDateValue = new PdfPCell(new Phrase(storageRecord.getOrderDate().toString(), fontEN));
        ordrDateValue.setUseBorderPadding(true);
        ordrDateValue.setBorderWidth(0f);
        //
        // Setting cell's background color
        //
//        cell2.setBackgroundColor(BaseColor.GRAY);
        //
        // Setting cell's individual border color
        //
//        cell2.setBorderWidthTop(1f);
//        cell2.setBorderColorTop(BaseColor.RED);
//        cell2.setBorderColorRight(BaseColor.GREEN);
//        cell2.setBorderColorBottom(BaseColor.BLUE);
//        cell2.setBorderColorLeft(BaseColor.BLACK);
        masterHead.addCell(ordrDateValue);

        PdfPCell auditCell = new PdfPCell(new Phrase("单据状态:", fontCN));
        auditCell.setUseBorderPadding(true);
        auditCell.setBorderWidth(0f);
        //
        // Setting cell's individual border width
        //
//        cell3.setBorderWidthTop(2f);
//        cell3.setBorderWidthRight(1f);
//        cell3.setBorderWidthBottom(2f);
//        cell3.setBorderWidthLeft(1f);
        masterHead.addCell(auditCell);

        String auditStatus = "待审核";
        String audit = storageRecord.getAudit();
        String state = storageRecord.getState();
        if(audit.equals("confirm")){
        	auditStatus = "已审核";
        }else if(audit.equals("active") && state.equals("confirm")){
        	auditStatus = "审核中";
        }else{
        	auditStatus = "待审核";
        }
        
       PdfPCell auditValue = new PdfPCell(new Phrase(auditStatus, fontCN));
       auditValue.setUseBorderPadding(true);
       auditValue.setBorderWidth(0f);
        //
        // Setting cell's individual border width
        //
//        cell4.setBorderWidthTop(2f);
//        cell4.setBorderWidthRight(1f);
//        cell4.setBorderWidthBottom(2f);
//        cell4.setBorderWidthLeft(1f);
        masterHead.addCell(auditValue);
        
        String providerNoLabel = "";
        String shortNameLabel = "";
        String providerNameLabel = "";
        
        String providerNoVal = "";
        String shortNameVal = "";
        String providerNameVal = "";
        
        if(storageRecord.getBillType().equals("BFDJ")){
            
            providerNoLabel = "报废来源:";
            shortNameLabel = "报废日期:";
            providerNameLabel = "报废原因:";
            
            providerNoVal = storageRecord.getOriginName();
            shortNameVal = storageRecord.getInvoiceDate().toString();
            providerNameVal = storageRecord.getPaymentTermLabel();
        	
        }
        
        PdfPCell providerNoCell = new PdfPCell(new Phrase(providerNoLabel, fontCN));
        providerNoCell.setBorder(0);
        masterHead.addCell(providerNoCell);
        PdfPCell providerNoValue = new PdfPCell(new Phrase(providerNoVal, fontCN));
        providerNoValue.setBorder(0);
        masterHead.addCell(providerNoValue);
        
        PdfPCell shortNameCell = new PdfPCell(new Phrase(shortNameLabel, fontCN));
        shortNameCell.setBorder(0);
        masterHead.addCell(shortNameCell);
        PdfPCell shortNameValue = new PdfPCell(new Phrase(shortNameVal, fontEN));
        shortNameValue.setBorder(0);
        masterHead.addCell(shortNameValue);

        //第一行结束
        masterHead.completeRow();
        
        PdfPCell orderNoCell = new PdfPCell(new PdfPCell(new Phrase("单号:", fontCN)));
        orderNoCell.setBorder(0);
        masterHead.addCell(orderNoCell);
        PdfPCell orderNoValue = new PdfPCell(new PdfPCell(new Phrase(storageRecord.getRecordNo(), fontEN)));
        orderNoValue.setBorder(0);
        orderNoValue.setColspan(3);
        masterHead.addCell(orderNoValue);
        
        PdfPCell providerNameCell = new PdfPCell(new Phrase(providerNameLabel, fontCN));
        providerNameCell.setBorder(0);
        masterHead.addCell(providerNameCell);
        PdfPCell providerNameValue = new PdfPCell(new Phrase(providerNameVal, fontCN));
        providerNameValue.setBorder(0);
        providerNameValue.setColspan(3);
        masterHead.addCell(providerNameValue);
        //第二行结束
        masterHead.completeRow();
        
        PdfPCell factoryNoCell = new PdfPCell(new PdfPCell(new Phrase("工厂编码:", fontCN)));
        factoryNoCell.setBorder(0);
        masterHead.addCell(factoryNoCell);
        PdfPCell factoryNoValue = new PdfPCell(new PdfPCell(new Phrase(storageRecord.getFactoryNo(), fontEN)));
        factoryNoValue.setBorder(0);
        masterHead.addCell(factoryNoValue);
        
        PdfPCell factoryNameCell = new PdfPCell(new PdfPCell(new Phrase("工厂名称:", fontCN)));
        factoryNameCell.setBorder(0);
        masterHead.addCell(factoryNameCell);
        PdfPCell factoryNameValue = new PdfPCell(new PdfPCell(new Phrase(storageRecord.getFactoryName(), fontCN)));
        factoryNameValue.setBorder(0);
        masterHead.addCell(factoryNameValue);
        
        PdfPCell employeeNameCell = new PdfPCell(new Phrase("经办人:", fontCN));
        employeeNameCell.setBorder(0);
        masterHead.addCell(employeeNameCell);
        PdfPCell employeeNameValue = new PdfPCell(new Phrase(storageRecord.getEmployeeName(), fontCN));
        employeeNameValue.setBorder(0);
        employeeNameValue.setColspan(3);
        masterHead.addCell(employeeNameValue);
        
        //第三行结束
        masterHead.completeRow();
        
        PdfPCell commentsCell = new PdfPCell(new Phrase("备注:", fontCN));
        commentsCell.setBorder(0);
        masterHead.addCell(commentsCell);
        PdfPCell commentsValue = new PdfPCell(new Phrase(storageRecord.getComments(), fontCN));
        commentsValue.setBorder(0);
        commentsValue.setColspan(7);
        masterHead.addCell(commentsValue);
        
        //第n行结束
        masterHead.completeRow();

        doc.add(masterHead);
//	    doc.add(line);
	    

        /*
        Image image = Image.getInstance("c://pdftest//smp.png");

        image.setAlignment(Image.ALIGN_RIGHT);
        // 设置边框
        image.setBorder(Image.BOX);
        image.setBorderWidth(2);
        image.setBorderColor(BaseColor.RED);
        // 设置图片大小
        
//        ScaleToFit有两个参数，指的是长和宽的最大值，但是图片的长宽比还是不会变的
//        ScaleAbsoluteHeight设置图片的高度，不管长宽比 ScaleAbsoluteWidth设置图片的宽度，不管长宽比
//        ScalePercent等比例缩放
        
//         image.scaleToFit(100, 100);
//         image.scaleAbsoluteHeight(100f);
//         image.scaleAbsoluteWidth(100f);

        image.scalePercent(50f);
        // 图片旋转30度
        image.setRotationDegrees(30);

        doc.add(image);
        */
        
        
        
        
        
	    //////////////////////////////////////////////////////////////////////////////////////////
	    
        PdfPTable details = new PdfPTable(7);
        details.setTotalWidth(new float[]{15, 70, 70, 80, 75, 130, 80});//520
        details.setLockedWidth(true);
        details.setSpacingBefore(10);

        PdfPCell sharpCell = new PdfPCell(new Phrase("序号", fontCN));
//        sharpCell.setBorder(0);
        sharpCell.setRowspan(4);
        sharpCell.setHorizontalAlignment(Element.ALIGN_CENTER);
        sharpCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        details.addCell(sharpCell);

        PdfPCell itemNoCell = new PdfPCell(new Phrase("物料编码", fontCN));
//        itemNoCell.setBorder(0);
//        itemNoCell.setBorderWidthTop(0);
        itemNoCell.setBorderWidthLeft(0);
        itemNoCell.setBorderWidthBottom(0);
        itemNoCell.setBorderWidthRight(0);
        itemNoCell.setColspan(2);
        details.addCell(itemNoCell);

        PdfPCell projectNoCell = new PdfPCell(new Phrase("项目号", fontCN));
//        projectNoCell.setBorder(0);
        projectNoCell.setBorderWidthLeft(0);
        projectNoCell.setBorderWidthBottom(0);
        projectNoCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(projectNoCell);

        PdfPCell priceAmountCell = new PdfPCell(new Phrase("数量", fontCN));
//        priceAmountCell.setBorder(0);
        priceAmountCell.setBorderWidthLeft(0);
        priceAmountCell.setBorderWidthBottom(0);
        priceAmountCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(priceAmountCell);

        PdfPCell arriveAmountBackCell = new PdfPCell(new Phrase("移出仓库编码", fontCN));
//        arriveAmountBackCell.setBorder(0);
        arriveAmountBackCell.setBorderWidthLeft(0);
        arriveAmountBackCell.setBorderWidthBottom(0);
        arriveAmountBackCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(arriveAmountBackCell);

        PdfPCell batchNoCell = new PdfPCell(new Phrase("批号", fontCN));
//        batchNoCell.setBorder(0);
        batchNoCell.setBorderWidthLeft(0);
        batchNoCell.setBorderWidthBottom(0);
        details.addCell(batchNoCell);
        
        details.completeRow();
        //第一行结束

        PdfPCell itemDescribeCell = new PdfPCell(new Phrase("名称", fontCN));
//        itemDescribeCell.setBorder(0);
        itemDescribeCell.setBorderWidthTop(0);
        itemDescribeCell.setBorderWidthLeft(0);
        itemDescribeCell.setBorderWidthBottom(0);
        itemDescribeCell.setColspan(3);
        details.addCell(itemDescribeCell);

        PdfPCell pieceQuantityCell = new PdfPCell(new Phrase("件数", fontCN));
//        pieceQuantityCell.setBorder(0);
        pieceQuantityCell.setBorderWidthTop(0);
        pieceQuantityCell.setBorderWidthLeft(0);
        pieceQuantityCell.setBorderWidthBottom(0);
        pieceQuantityCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(pieceQuantityCell);

        PdfPCell orderAmountOldsCell = new PdfPCell(new Phrase("移出地", fontCN));
//        orderAmountOldsCell.setBorder(0);
        orderAmountOldsCell.setBorderWidthTop(0);
        orderAmountOldsCell.setBorderWidthLeft(0);
        orderAmountOldsCell.setBorderWidthBottom(0);
        orderAmountOldsCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(orderAmountOldsCell);

        PdfPCell batchDescribeCell = new PdfPCell(new Phrase("批号说明", fontCN));
//        batchDescribeCell.setBorder(0);
        batchDescribeCell.setBorderWidthTop(0);
        batchDescribeCell.setBorderWidthLeft(0);
        batchDescribeCell.setBorderWidthBottom(0);
        details.addCell(batchDescribeCell);

        details.completeRow();
        //第二行结束

        PdfPCell itemPropertyCell = new PdfPCell(new Phrase("规格", fontCN));
//        itemPropertyCell.setBorder(0);
        itemPropertyCell.setBorderWidthTop(0);
        itemPropertyCell.setBorderWidthLeft(0);
        itemPropertyCell.setBorderWidthBottom(0);
        itemPropertyCell.setBorderWidthRight(0);
        itemPropertyCell.setColspan(2);
        details.addCell(itemPropertyCell);

        PdfPCell unitNameCell = new PdfPCell(new Phrase("单位", fontCN));
//        unitNameCell.setBorder(0);
        unitNameCell.setBorderWidthTop(0);
        unitNameCell.setBorderWidthLeft(0);
        unitNameCell.setBorderWidthBottom(0);
        unitNameCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(unitNameCell);

        PdfPCell itemPriceCell = new PdfPCell(new Phrase("单位成本", fontCN));
//        itemPriceCell.setBorder(0);
        itemPriceCell.setBorderWidthTop(0);
        itemPriceCell.setBorderWidthLeft(0);
        itemPriceCell.setBorderWidthBottom(0);
        itemPriceCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(itemPriceCell);

        PdfPCell orderAmountTaxsCell = new PdfPCell(new Phrase("移入仓库编码", fontCN));
//        orderAmountTaxsCell.setBorder(0);
        orderAmountTaxsCell.setBorderWidthTop(0);
        orderAmountTaxsCell.setBorderWidthLeft(0);
        orderAmountTaxsCell.setBorderWidthBottom(0);
        orderAmountTaxsCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(orderAmountTaxsCell);

        PdfPCell commentssCell = new PdfPCell(new Phrase("备注", fontCN));
//        commentssCell.setBorder(0);
        commentssCell.setBorderWidthTop(0);
        commentssCell.setBorderWidthLeft(0);
        commentssCell.setRowspan(2);
        details.addCell(commentssCell);

        details.completeRow();
        //第三行结束

        PdfPCell floorNoCell = new PdfPCell(new Phrase("有效日期", fontCN));
//        floorNoCell.setBorder(0);
        floorNoCell.setBorderWidthTop(0);
        floorNoCell.setBorderWidthLeft(0);
        floorNoCell.setBorderWidthRight(0);
        floorNoCell.setColspan(2);
        details.addCell(floorNoCell);

        PdfPCell storageNoCell = new PdfPCell(new Phrase("复检日期", fontCN));
//        storageNoCell.setBorder(0);
        storageNoCell.setBorderWidthTop(0);
        storageNoCell.setBorderWidthLeft(0);
        storageNoCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(storageNoCell);

        PdfPCell orderAmountCell = new PdfPCell(new Phrase("金额", fontCN));
//        orderAmountCell.setBorder(0);
        orderAmountCell.setBorderWidthTop(0);
        orderAmountCell.setBorderWidthLeft(0);
        orderAmountCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(orderAmountCell);

        PdfPCell orderAmountTotalsCell = new PdfPCell(new Phrase("移入地", fontCN));
//        orderAmountTotalsCell.setBorder(0);
        orderAmountTotalsCell.setBorderWidthTop(0);
        orderAmountTotalsCell.setBorderWidthLeft(0);
        orderAmountTotalsCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(orderAmountTotalsCell);

        details.completeRow();
        //第四行结束
        
        
//        doc.add(details);
        
        ////////////////////////////////////////////////////////////////////////////////////////////
        
        
	    //////////////////////////////////////////////////////////////////////////////////////////
        List<StorageRecordDetail> storageRecordDetails = storageRecordDetailService.getByMasterID(fID);
        if(storageRecordDetails.size()>0){
    	    
//            PdfPTable detailsValue = new PdfPTable(8);
//            
//            detailsValue.setTotalWidth(new float[]{20, 70, 70, 80, 80, 80, 60, 60});//520
//            detailsValue.setLockedWidth(true);
//            detailsValue.setSpacingBefore(10);
            
            for(int i=0;i<storageRecordDetails.size();i++){
            	StorageRecordDetail storageRecordDetail = storageRecordDetails.get(i);

            	//序号
            	String rowNo = String.valueOf(i+1);
                PdfPCell sharpValue = new PdfPCell(new Phrase(rowNo, fontEN));
//                sharpValue.setBorder(0);
                sharpValue.setBorderWidthTop(0);
                sharpValue.setRowspan(4);
                sharpValue.setHorizontalAlignment(Element.ALIGN_CENTER);
                sharpValue.setVerticalAlignment(Element.ALIGN_MIDDLE);
                details.addCell(sharpValue);

                PdfPCell itemNoValue = new PdfPCell(new Phrase(storageRecordDetail.getItemNo(), fontEN));
//                itemNoValue.setBorder(0);
                itemNoValue.setBorderWidthTop(0);
                itemNoValue.setBorderWidthLeft(0);
                itemNoValue.setBorderWidthBottom(0);
                itemNoValue.setBorderWidthRight(0);
                itemNoValue.setColspan(2);
                details.addCell(itemNoValue);

                PdfPCell projectNoValue = new PdfPCell(new Phrase(storageRecordDetail.getProjectNo(), fontEN));
//                projectNoValue.setBorder(0);
                projectNoValue.setBorderWidthTop(0);
                projectNoValue.setBorderWidthLeft(0);
                projectNoValue.setBorderWidthBottom(0);
                projectNoValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
                details.addCell(projectNoValue);

                PdfPCell priceAmountValue = new PdfPCell(new Phrase(storageRecordDetail.getPriceAmount().toString(), fontEN));
//                priceAmountValue.setBorder(0);
                priceAmountValue.setBorderWidthTop(0);
                priceAmountValue.setBorderWidthLeft(0);
                priceAmountValue.setBorderWidthBottom(0);
                priceAmountValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
                details.addCell(priceAmountValue);

                PdfPCell arriveAmountBackValue = new PdfPCell(new Phrase(storageRecordDetail.getProviderNo(), fontCN));
//                arriveAmountBackValue.setBorder(0);
                arriveAmountBackValue.setBorderWidthTop(0);
                arriveAmountBackValue.setBorderWidthLeft(0);
                arriveAmountBackValue.setBorderWidthBottom(0);
                arriveAmountBackValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
                details.addCell(arriveAmountBackValue);

                PdfPCell batchNoValue = new PdfPCell(new Phrase(storageRecordDetail.getBatchNo(), fontEN));
//              batchNoValue.setBorder(0);
                batchNoValue.setBorderWidthTop(0);
                batchNoValue.setBorderWidthBottom(0);
                batchNoValue.setBorderWidthLeft(0);
                details.addCell(batchNoValue);

                details.completeRow();
                //第一行结束
 
                PdfPCell itemDescribeValue = new PdfPCell(new Phrase(storageRecordDetail.getItemName(), fontCN));
//              itemDescribeValue.setBorder(0);
                itemDescribeValue.setBorderWidthTop(0);
                itemDescribeValue.setBorderWidthLeft(0);
                itemDescribeValue.setBorderWidthBottom(0);
                itemDescribeValue.setColspan(3);
                details.addCell(itemDescribeValue);

                PdfPCell pieceQuantityValue = new PdfPCell(new Phrase(storageRecordDetail.getPieceQuantity().toString(), fontEN));
//                pieceQuantityValue.setBorder(0);
                pieceQuantityValue.setBorderWidthTop(0);
                pieceQuantityValue.setBorderWidthLeft(0);
                pieceQuantityValue.setBorderWidthBottom(0);
                pieceQuantityValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
                details.addCell(pieceQuantityValue);

              PdfPCell orderAmountOldsValue = new PdfPCell(new Phrase(storageRecordDetail.getProviderName(), fontCN));
//              orderAmountOldsValue.setBorder(0);
              orderAmountOldsValue.setBorderWidthTop(0);
              orderAmountOldsValue.setBorderWidthLeft(0);
              orderAmountOldsValue.setBorderWidthBottom(0);
              orderAmountOldsValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
              details.addCell(orderAmountOldsValue);

              PdfPCell tbatchDescribeValue = new PdfPCell(new Phrase(storageRecordDetail.getBatchDescribe(), fontCN));
//              tbatchDescribeValue.setBorder(0);
              tbatchDescribeValue.setBorderWidthTop(0);
              tbatchDescribeValue.setBorderWidthLeft(0);
              tbatchDescribeValue.setBorderWidthBottom(0);
              tbatchDescribeValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
              details.addCell(tbatchDescribeValue);

              details.completeRow();
              //第二行结束

              PdfPCell itemPropertyValue = new PdfPCell(new Phrase(storageRecordDetail.getItemProperty(), fontCN));
//              itemPropertyValue.setBorder(0);
              itemPropertyValue.setBorderWidthTop(0);
              itemPropertyValue.setBorderWidthLeft(0);
              itemPropertyValue.setBorderWidthBottom(0);
              itemPropertyValue.setBorderWidthRight(0);
              itemPropertyValue.setColspan(2);
              details.addCell(itemPropertyValue);

              PdfPCell unitNameValue = new PdfPCell(new Phrase(storageRecordDetail.getUnitName(), fontCN));
//              unitNameValue.setBorder(0);
              unitNameValue.setBorderWidthTop(0);
              unitNameValue.setBorderWidthLeft(0);
              unitNameValue.setBorderWidthBottom(0);
              unitNameValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
              details.addCell(unitNameValue);

              PdfPCell itemPriceValue = new PdfPCell(new Phrase("", fontEN));
//              itemPriceValue.setBorder(0);
              itemPriceValue.setBorderWidthTop(0);
              itemPriceValue.setBorderWidthLeft(0);
              itemPriceValue.setBorderWidthBottom(0);
              itemPriceValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
              details.addCell(itemPriceValue);

              PdfPCell orderAmountTaxValue = new PdfPCell(new Phrase(storageRecordDetail.getStorageNo(), fontCN));
//              orderAmountTaxValue.setBorder(0);
              orderAmountTaxValue.setBorderWidthTop(0);
              orderAmountTaxValue.setBorderWidthLeft(0);
              orderAmountTaxValue.setBorderWidthBottom(0);
              orderAmountTaxValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
              details.addCell(orderAmountTaxValue);

              PdfPCell commentssValue = new PdfPCell(new Phrase(storageRecordDetail.getComments(), fontCN));
//              commentssValue.setBorder(0);
              commentssValue.setBorderWidthTop(0);
              commentssValue.setBorderWidthLeft(0);
              commentssValue.setRowspan(2);
              details.addCell(commentssValue);

              details.completeRow();
              //第三行结束
              

              PdfPCell floorNoValue = new PdfPCell(new Phrase(storageRecordDetail.getValidDate()==null?"":storageRecordDetail.getValidDate().toString().toString(), fontEN));
//              floorNoValue.setBorder(0);
              floorNoValue.setBorderWidthTop(0);
              floorNoValue.setBorderWidthLeft(0);
              floorNoValue.setBorderWidthRight(0);
              floorNoValue.setColspan(2);
              details.addCell(floorNoValue);

              PdfPCell storageNoValue = new PdfPCell(new Phrase(storageRecordDetail.getCheckoutAgainDate()==null?"":storageRecordDetail.getCheckoutAgainDate().toString(), fontEN));
//              storageNoValue.setBorder(0);
              storageNoValue.setBorderWidthTop(0);
              storageNoValue.setBorderWidthLeft(0);
              storageNoValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
              details.addCell(storageNoValue);

              PdfPCell orderAmountValue = new PdfPCell(new Phrase("", fontEN));
//              orderAmountValue.setBorder(0);
              orderAmountValue.setBorderWidthTop(0);
              orderAmountValue.setBorderWidthLeft(0);
              orderAmountValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
              details.addCell(orderAmountValue);

              PdfPCell orderAmountTotalValue = new PdfPCell(new Phrase(storageRecordDetail.getFloorNo(), fontCN));
//              orderAmountTotalValue.setBorder(0);
              orderAmountTotalValue.setBorderWidthTop(0);
              orderAmountTotalValue.setBorderWidthLeft(0);
              orderAmountTotalValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
              details.addCell(orderAmountTotalValue);

              details.completeRow();
              //第四行结束
              
            }
            
            doc.add(details);
      	
        }
        ////////////////////////////////////////////////////////////////////////////////////////////
        
//	    doc.add(line);

	    
        PdfPTable masterFoot = new PdfPTable(8);
        
        masterFoot.setTotalWidth(new float[]{45, 85, 45, 85, 45, 85, 45, 85});
        masterFoot.setLockedWidth(true);
//        masterFoot.setSpacingBefore(10);

        PdfPCell detailsCountCell = new PdfPCell(new Phrase("笔数:", fontCN));
//        detailsCountCell.setBorder(0);
        detailsCountCell.setBorderWidthTop(0);
        detailsCountCell.setBorderWidthBottom(0);
        detailsCountCell.setBorderWidthRight(0);
        masterFoot.addCell(detailsCountCell);

        PdfPCell detailsCountValue = new PdfPCell(new Phrase(String.valueOf(storageRecord.getDetailsCount()), fontEN));
        detailsCountValue.setBorderWidthTop(0);
        detailsCountValue.setBorderWidthLeft(0);
        detailsCountValue.setBorderWidthBottom(0);
        detailsCountValue.setColspan(7);
        masterFoot.addCell(detailsCountValue);

        //第一行结束
        masterFoot.completeRow();

        PdfPCell itemAmountCell = new PdfPCell(new Phrase("数量合计:", fontCN));
//        itemAmountCell.setBorder(0);
        itemAmountCell.setBorderWidthTop(0);
        itemAmountCell.setBorderWidthRight(0);
        masterFoot.addCell(itemAmountCell);

        PdfPCell itemAmountValue = new PdfPCell(new Phrase(storageRecord.getItemAmount().toString(), fontEN));
        itemAmountValue.setBorderWidthTop(0);
        itemAmountValue.setBorderWidthLeft(0);
        itemAmountValue.setColspan(7);
        masterFoot.addCell(itemAmountValue);


        //第二行结束
        masterFoot.completeRow();


        doc.add(masterFoot);
        
        
        
	    
        PdfPTable masterTail = new PdfPTable(8);
        
        masterTail.setTotalWidth(new float[]{45, 65, 45, 105, 45, 65, 45, 105});
        masterTail.setLockedWidth(true);
        masterTail.setSpacingBefore(10);

        PdfPCell cUsernameCell = new PdfPCell(new Phrase("制单:", fontCN));
        cUsernameCell.setBorder(0);
        masterTail.addCell(cUsernameCell);

        PdfPCell cUsernameValue = new PdfPCell(new Phrase(storageRecord.getcUsername(), fontCN));
        cUsernameValue.setBorder(0);
        masterTail.addCell(cUsernameValue);

        PdfPCell cDatetimeCell = new PdfPCell(new Phrase("制单时间:", fontCN));
        cDatetimeCell.setBorder(0);
        masterTail.addCell(cDatetimeCell);

        PdfPCell cDatetimeValue = new PdfPCell(new Phrase(storageRecord.getcDatetime().toString(), fontEN));
        cDatetimeValue.setBorder(0);
        masterTail.addCell(cDatetimeValue);

        PdfPCell tUsernameCell = new PdfPCell(new Phrase("审核:", fontCN));
        tUsernameCell.setBorder(0);
        masterTail.addCell(tUsernameCell);

        PdfPCell tUsernameValue = new PdfPCell(new Phrase(storageRecord.gettUsername(), fontCN));
        tUsernameValue.setBorder(0);
        masterTail.addCell(tUsernameValue);

        PdfPCell tDatetimeCell = new PdfPCell(new Phrase("审核时间:", fontCN));
        tDatetimeCell.setBorder(0);
        masterTail.addCell(tDatetimeCell);

        PdfPCell tDatetimeValue = new PdfPCell(new Phrase(storageRecord.gettDatetime()==null?"":storageRecord.gettDatetime().toString(), fontEN));
        tDatetimeValue.setBorder(0);
        masterTail.addCell(tDatetimeValue);


        masterTail.completeRow();
        

        doc.add(masterTail);
	    
        Chunk printTimeChunk = new Chunk("打印时间: ",fontCN);
        String printTime = Utils.getCurrentDateTime().toString();
        Paragraph printTimeParagraph = new Paragraph(printTimeChunk);
        Chunk printTimeValueChunk = new Chunk(printTime,fontEN);
        printTimeParagraph.add(printTimeValueChunk);
        printTimeParagraph.setAlignment(Element.ALIGN_RIGHT);
	    doc.add(printTimeParagraph);

	    
//	    doc.close();
	    
	    
	    
//        int pageNumber = doc.getPageNumber();
//        System.out.println(pageNumber);
//	    Rectangle rect = doc.getPageSize();
//	    System.out.println("rect.getHeight()-->"+rect.getHeight());
//	    System.out.println("rect.getWidth()-->"+rect.getWidth());
//	    System.out.println("rect.getLeft()-->"+rect.getLeft());
//	    System.out.println("rect.getTop()-->"+rect.getTop());
//	    System.out.println("rect.getBottom()-->"+rect.getBottom());
//	    System.out.println("rect.getRight()-->"+rect.getRight());
//	    System.out.println("rect.getBorder()-->"+rect.getBorder());
//	    System.out.println("rect.getBorderWidth()-->"+rect.getBorderWidth());
//	    System.out.println("rect.getBorderWidthTop()-->"+rect.getBorderWidthTop());
//	    System.out.println("rect.getBorderWidthLeft()-->"+rect.getBorderWidthLeft());
//	    System.out.println("rect.getBorderWidthBottom()-->"+rect.getBorderWidthBottom());
//	    System.out.println("rect.getBorderWidthRight()-->"+rect.getBorderWidthRight());

	}
	
	
	//其他入库单/出库单/成本开账调整单/销毁出库单打印
	@Override
	public void invQTRKPrintPDF(String fID, Document doc) throws Exception {
		
//	@Test
//	public void storageRecordPrintPDF() throws Exception {
//		System.out.println("fID-->"+id);
		
//	    Document doc = new Document();// 创建一个PDF文档，我们的PDF内容都写在上面
	    
//	    PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(new File("c://pdftest//storageRecord.pdf"))); // 将pdf文档写入文件

//		String fID = "bf61ec2bc8163a3ad3d8572ad2fee7c6";
		StorageRecord storageRecord = storageRecordService.getByID(fID);
	   
//	    response.setContentType("application/pdf");
//	    PdfWriter.getInstance(doc, response.getOutputStream());
//	    
//	    doc.open();
	    
	    Font fontEN = new Font(BaseFont.createFont(),9);
	    BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);  	    
//	    Font font = new Font(baseFont, 10, Font.ITALIC);
	    Font fontCN = new Font(baseFont, 9);
	    Paragraph pEnterpriseName = new Paragraph(storageRecord.getEnterpriseName(),fontCN);
	    // 居中显示
	    pEnterpriseName.setAlignment(Element.ALIGN_CENTER);
	    pEnterpriseName.setSpacingAfter(-10);
	    Paragraph pBillTypeName = new Paragraph(storageRecord.getBillTypeName(),new Font(baseFont,20));
	    // 居中显示
	    pBillTypeName.setAlignment(Element.ALIGN_CENTER);
	    LineSeparator line = new LineSeparator(1f, 100, BaseColor.BLACK, Element.ALIGN_CENTER, -5f);

	    
	    
	    
	    
	    
	    doc.add(pEnterpriseName);
	    doc.add(pBillTypeName);
	    doc.add(line);
	    
	    
        PdfPTable masterHead = new PdfPTable(8);
        
//        masterHead.setTotalWidth(new float[]{60, 200, 60, 200});
        masterHead.setTotalWidth(new float[]{45, 85, 45, 85, 45, 85, 45, 85});
        masterHead.setLockedWidth(true);
        masterHead.setSpacingBefore(10);
        
        PdfPCell ordrDateCell = new PdfPCell(new Phrase("单据日期:", fontCN));
        ordrDateCell.setUseBorderPadding(true);
        //
        // Setting cell's border width and color
        //
        ordrDateCell.setBorderWidth(0f);
//        ordrDateCell.setBorderColor(BaseColor.BLUE);
        masterHead.addCell(ordrDateCell);

        PdfPCell ordrDateValue = new PdfPCell(new Phrase(storageRecord.getOrderDate().toString(), fontEN));
        ordrDateValue.setUseBorderPadding(true);
        ordrDateValue.setBorderWidth(0f);
        //
        // Setting cell's background color
        //
//        cell2.setBackgroundColor(BaseColor.GRAY);
        //
        // Setting cell's individual border color
        //
//        cell2.setBorderWidthTop(1f);
//        cell2.setBorderColorTop(BaseColor.RED);
//        cell2.setBorderColorRight(BaseColor.GREEN);
//        cell2.setBorderColorBottom(BaseColor.BLUE);
//        cell2.setBorderColorLeft(BaseColor.BLACK);
        masterHead.addCell(ordrDateValue);

        PdfPCell auditCell = new PdfPCell(new Phrase("单据状态:", fontCN));
        auditCell.setUseBorderPadding(true);
        auditCell.setBorderWidth(0f);
        //
        // Setting cell's individual border width
        //
//        cell3.setBorderWidthTop(2f);
//        cell3.setBorderWidthRight(1f);
//        cell3.setBorderWidthBottom(2f);
//        cell3.setBorderWidthLeft(1f);
        masterHead.addCell(auditCell);

        String auditStatus = "待审核";
        String audit = storageRecord.getAudit();
        String state = storageRecord.getState();
        if(audit.equals("confirm")){
        	auditStatus = "已审核";
        }else if(audit.equals("active") && state.equals("confirm")){
        	auditStatus = "审核中";
        }else{
        	auditStatus = "待审核";
        }
        
       PdfPCell auditValue = new PdfPCell(new Phrase(auditStatus, fontCN));
       auditValue.setUseBorderPadding(true);
       auditValue.setBorderWidth(0f);
        //
        // Setting cell's individual border width
        //
//        cell4.setBorderWidthTop(2f);
//        cell4.setBorderWidthRight(1f);
//        cell4.setBorderWidthBottom(2f);
//        cell4.setBorderWidthLeft(1f);
        masterHead.addCell(auditValue);
        
        String providerNoLabel = "";
        String shortNameLabel = "";
        String providerNameLabel = "";
        
        String providerNoVal = "";
        String shortNameVal = "";
        String providerNameVal = "";
        
        if(storageRecord.getBillType().equals("CBKZ")){
            
            providerNoLabel = "仓库编码:";
            shortNameLabel = "名称:";
            providerNameLabel = "库存地:";
            
            providerNoVal = storageRecord.getStorageNo();
            shortNameVal = storageRecord.getStorageName();
            providerNameVal = storageRecord.getFloorNo();
        	
        }
        
        if(storageRecord.getBillType().equals("XHCK")){
            
            providerNoLabel = "销毁来源:";
            shortNameLabel = "销毁日期:";
            providerNameLabel = "销毁原因:";
            
            providerNoVal = storageRecord.getOriginName();
            shortNameVal = storageRecord.getInvoiceDate().toString();
            providerNameVal = storageRecord.getPaymentTermLabel();
        	
        }
        
        if(storageRecord.getBillType().equals("QTRK") || storageRecord.getBillType().equals("QTCK")){
            
            providerNoLabel = "交易部门:";
            shortNameLabel = "部门名称:";
            providerNameLabel = "长名称:";
            
            providerNoVal = storageRecord.getProviderNo();
            shortNameVal = storageRecord.getShortName();
            providerNameVal = storageRecord.getProviderName();
        	
        }
        
        PdfPCell providerNoCell = new PdfPCell(new Phrase(providerNoLabel, fontCN));
        providerNoCell.setBorder(0);
        masterHead.addCell(providerNoCell);
        PdfPCell providerNoValue = new PdfPCell(new Phrase(providerNoVal, fontCN));
        providerNoValue.setBorder(0);
        masterHead.addCell(providerNoValue);
        
        PdfPCell shortNameCell = new PdfPCell(new Phrase(shortNameLabel, fontCN));
        shortNameCell.setBorder(0);
        masterHead.addCell(shortNameCell);
        PdfPCell shortNameValue = new PdfPCell(new Phrase(shortNameVal, fontCN));
        shortNameValue.setBorder(0);
        masterHead.addCell(shortNameValue);

        //第一行结束
        masterHead.completeRow();
        
        PdfPCell orderNoCell = new PdfPCell(new PdfPCell(new Phrase("单号:", fontCN)));
        orderNoCell.setBorder(0);
        masterHead.addCell(orderNoCell);
        PdfPCell orderNoValue = new PdfPCell(new PdfPCell(new Phrase(storageRecord.getRecordNo(), fontEN)));
        orderNoValue.setBorder(0);
        orderNoValue.setColspan(3);
        masterHead.addCell(orderNoValue);
        
        PdfPCell providerNameCell = new PdfPCell(new Phrase(providerNameLabel, fontCN));
        providerNameCell.setBorder(0);
        masterHead.addCell(providerNameCell);
        PdfPCell providerNameValue = new PdfPCell(new Phrase(providerNameVal, fontCN));
        providerNameValue.setBorder(0);
        providerNameValue.setColspan(3);
        masterHead.addCell(providerNameValue);
        //第二行结束
        masterHead.completeRow();
        
        PdfPCell factoryNoCell = new PdfPCell(new PdfPCell(new Phrase("工厂编码:", fontCN)));
        factoryNoCell.setBorder(0);
        masterHead.addCell(factoryNoCell);
        PdfPCell factoryNoValue = new PdfPCell(new PdfPCell(new Phrase(storageRecord.getFactoryNo(), fontEN)));
        factoryNoValue.setBorder(0);
        masterHead.addCell(factoryNoValue);
        
        PdfPCell factoryNameCell = new PdfPCell(new PdfPCell(new Phrase("工厂名称:", fontCN)));
        factoryNameCell.setBorder(0);
        masterHead.addCell(factoryNameCell);
        PdfPCell factoryNameValue = new PdfPCell(new PdfPCell(new Phrase(storageRecord.getFactoryName(), fontCN)));
        factoryNameValue.setBorder(0);
        masterHead.addCell(factoryNameValue);
        
        PdfPCell employeeNameCell = new PdfPCell(new Phrase("经办人:", fontCN));
        employeeNameCell.setBorder(0);
        masterHead.addCell(employeeNameCell);
        PdfPCell employeeNameValue = new PdfPCell(new Phrase(storageRecord.getEmployeeName(), fontCN));
        employeeNameValue.setBorder(0);
        employeeNameValue.setColspan(3);
        masterHead.addCell(employeeNameValue);
        
        //第三行结束
        masterHead.completeRow();
        
        PdfPCell commentsCell = new PdfPCell(new Phrase("备注:", fontCN));
        commentsCell.setBorder(0);
        masterHead.addCell(commentsCell);
        PdfPCell commentsValue = new PdfPCell(new Phrase(storageRecord.getComments(), fontCN));
        commentsValue.setBorder(0);
        commentsValue.setColspan(7);
        masterHead.addCell(commentsValue);
        
        //第n行结束
        masterHead.completeRow();

        doc.add(masterHead);
//	    doc.add(line);
	    

        /*
        Image image = Image.getInstance("c://pdftest//smp.png");

        image.setAlignment(Image.ALIGN_RIGHT);
        // 设置边框
        image.setBorder(Image.BOX);
        image.setBorderWidth(2);
        image.setBorderColor(BaseColor.RED);
        // 设置图片大小
        
//        ScaleToFit有两个参数，指的是长和宽的最大值，但是图片的长宽比还是不会变的
//        ScaleAbsoluteHeight设置图片的高度，不管长宽比 ScaleAbsoluteWidth设置图片的宽度，不管长宽比
//        ScalePercent等比例缩放
        
//         image.scaleToFit(100, 100);
//         image.scaleAbsoluteHeight(100f);
//         image.scaleAbsoluteWidth(100f);

        image.scalePercent(50f);
        // 图片旋转30度
        image.setRotationDegrees(30);

        doc.add(image);
        */
        
        
        
        
        
	    //////////////////////////////////////////////////////////////////////////////////////////
	    
        PdfPTable details = new PdfPTable(7);
        details.setTotalWidth(new float[]{15, 70, 70, 80, 75, 65, 145});//520
        details.setLockedWidth(true);
        details.setSpacingBefore(10);

        PdfPCell sharpCell = new PdfPCell(new Phrase("序号", fontCN));
//        sharpCell.setBorder(0);
        sharpCell.setRowspan(4);
        sharpCell.setHorizontalAlignment(Element.ALIGN_CENTER);
        sharpCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        details.addCell(sharpCell);

        PdfPCell itemNoCell = new PdfPCell(new Phrase("物料编码", fontCN));
//        itemNoCell.setBorder(0);
//        itemNoCell.setBorderWidthTop(0);
        itemNoCell.setBorderWidthLeft(0);
        itemNoCell.setBorderWidthBottom(0);
        itemNoCell.setBorderWidthRight(0);
        itemNoCell.setColspan(2);
        details.addCell(itemNoCell);

        PdfPCell projectNoCell = new PdfPCell(new Phrase("项目号", fontCN));
//        projectNoCell.setBorder(0);
        projectNoCell.setBorderWidthLeft(0);
        projectNoCell.setBorderWidthBottom(0);
        projectNoCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(projectNoCell);

        PdfPCell priceAmountCell = new PdfPCell(new Phrase("数量", fontCN));
//        priceAmountCell.setBorder(0);
        priceAmountCell.setBorderWidthLeft(0);
        priceAmountCell.setBorderWidthBottom(0);
        priceAmountCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(priceAmountCell);

        PdfPCell arriveAmountBackCell = new PdfPCell(new Phrase("有效日期", fontCN));
//        arriveAmountBackCell.setBorder(0);
        arriveAmountBackCell.setBorderWidthLeft(0);
        arriveAmountBackCell.setBorderWidthBottom(0);
        arriveAmountBackCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(arriveAmountBackCell);

        PdfPCell batchNoCell = new PdfPCell(new Phrase("批号", fontCN));
//        batchNoCell.setBorder(0);
        batchNoCell.setBorderWidthLeft(0);
        batchNoCell.setBorderWidthBottom(0);
        details.addCell(batchNoCell);
        
        details.completeRow();
        //第一行结束

        PdfPCell itemDescribeCell = new PdfPCell(new Phrase("名称", fontCN));
//        itemDescribeCell.setBorder(0);
        itemDescribeCell.setBorderWidthTop(0);
        itemDescribeCell.setBorderWidthLeft(0);
        itemDescribeCell.setBorderWidthBottom(0);
        itemDescribeCell.setColspan(3);
        details.addCell(itemDescribeCell);

        PdfPCell pieceQuantityCell = new PdfPCell(new Phrase("件数", fontCN));
//        pieceQuantityCell.setBorder(0);
        pieceQuantityCell.setBorderWidthTop(0);
        pieceQuantityCell.setBorderWidthLeft(0);
        pieceQuantityCell.setBorderWidthBottom(0);
        pieceQuantityCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(pieceQuantityCell);

        PdfPCell orderAmountOldsCell = new PdfPCell(new Phrase("复检日期", fontCN));
//        orderAmountOldsCell.setBorder(0);
        orderAmountOldsCell.setBorderWidthTop(0);
        orderAmountOldsCell.setBorderWidthLeft(0);
        orderAmountOldsCell.setBorderWidthBottom(0);
        orderAmountOldsCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(orderAmountOldsCell);

        PdfPCell batchDescribeCell = new PdfPCell(new Phrase("批号说明", fontCN));
//        batchDescribeCell.setBorder(0);
        batchDescribeCell.setBorderWidthTop(0);
        batchDescribeCell.setBorderWidthLeft(0);
        batchDescribeCell.setBorderWidthBottom(0);
        details.addCell(batchDescribeCell);

        details.completeRow();
        //第二行结束

        PdfPCell itemPropertyCell = new PdfPCell(new Phrase("规格", fontCN));
//        itemPropertyCell.setBorder(0);
        itemPropertyCell.setBorderWidthTop(0);
        itemPropertyCell.setBorderWidthLeft(0);
        itemPropertyCell.setBorderWidthBottom(0);
        itemPropertyCell.setBorderWidthRight(0);
        itemPropertyCell.setColspan(2);
        details.addCell(itemPropertyCell);

        PdfPCell unitNameCell = new PdfPCell(new Phrase("单位", fontCN));
//        unitNameCell.setBorder(0);
        unitNameCell.setBorderWidthTop(0);
        unitNameCell.setBorderWidthLeft(0);
        unitNameCell.setBorderWidthBottom(0);
        unitNameCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(unitNameCell);

        PdfPCell itemPriceCell = new PdfPCell(new Phrase("单位成本", fontCN));
//        itemPriceCell.setBorder(0);
        itemPriceCell.setBorderWidthTop(0);
        itemPriceCell.setBorderWidthLeft(0);
        itemPriceCell.setBorderWidthBottom(0);
        itemPriceCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(itemPriceCell);

        PdfPCell orderAmountTaxsCell = new PdfPCell(new Phrase("", fontCN));
//        orderAmountTaxsCell.setBorder(0);
        orderAmountTaxsCell.setBorderWidthTop(0);
        orderAmountTaxsCell.setBorderWidthLeft(0);
        orderAmountTaxsCell.setBorderWidthBottom(0);
        orderAmountTaxsCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(orderAmountTaxsCell);

        PdfPCell commentssCell = new PdfPCell(new Phrase("备注", fontCN));
//        commentssCell.setBorder(0);
        commentssCell.setBorderWidthTop(0);
        commentssCell.setBorderWidthLeft(0);
        commentssCell.setRowspan(2);
        details.addCell(commentssCell);

        details.completeRow();
        //第三行结束

        PdfPCell floorNoCell = new PdfPCell(new Phrase("库存地", fontCN));
//        floorNoCell.setBorder(0);
        floorNoCell.setBorderWidthTop(0);
        floorNoCell.setBorderWidthLeft(0);
        floorNoCell.setBorderWidthRight(0);
        floorNoCell.setColspan(2);
        details.addCell(floorNoCell);

        PdfPCell storageNoCell = new PdfPCell(new Phrase("仓库编码", fontCN));
//        storageNoCell.setBorder(0);
        storageNoCell.setBorderWidthTop(0);
        storageNoCell.setBorderWidthLeft(0);
        storageNoCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(storageNoCell);

        PdfPCell orderAmountCell = new PdfPCell(new Phrase("金额", fontCN));
//        orderAmountCell.setBorder(0);
        orderAmountCell.setBorderWidthTop(0);
        orderAmountCell.setBorderWidthLeft(0);
        orderAmountCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(orderAmountCell);

        PdfPCell orderAmountTotalsCell = new PdfPCell(new Phrase("", fontCN));
//        orderAmountTotalsCell.setBorder(0);
        orderAmountTotalsCell.setBorderWidthTop(0);
        orderAmountTotalsCell.setBorderWidthLeft(0);
        orderAmountTotalsCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(orderAmountTotalsCell);

        details.completeRow();
        //第四行结束
        
        
//        doc.add(details);
        
        ////////////////////////////////////////////////////////////////////////////////////////////
        
        
	    //////////////////////////////////////////////////////////////////////////////////////////
        List<StorageRecordDetail> storageRecordDetails = storageRecordDetailService.getByMasterID(fID);
        if(storageRecordDetails.size()>0){
    	    
//            PdfPTable detailsValue = new PdfPTable(8);
//            
//            detailsValue.setTotalWidth(new float[]{20, 70, 70, 80, 80, 80, 60, 60});//520
//            detailsValue.setLockedWidth(true);
//            detailsValue.setSpacingBefore(10);
            
            for(int i=0;i<storageRecordDetails.size();i++){
            	StorageRecordDetail storageRecordDetail = storageRecordDetails.get(i);

            	//序号
            	String rowNo = String.valueOf(i+1);
                PdfPCell sharpValue = new PdfPCell(new Phrase(rowNo, fontEN));
//                sharpValue.setBorder(0);
                sharpValue.setBorderWidthTop(0);
                sharpValue.setRowspan(4);
                sharpValue.setHorizontalAlignment(Element.ALIGN_CENTER);
                sharpValue.setVerticalAlignment(Element.ALIGN_MIDDLE);
                details.addCell(sharpValue);

                PdfPCell itemNoValue = new PdfPCell(new Phrase(storageRecordDetail.getItemNo(), fontEN));
//                itemNoValue.setBorder(0);
                itemNoValue.setBorderWidthTop(0);
                itemNoValue.setBorderWidthLeft(0);
                itemNoValue.setBorderWidthBottom(0);
                itemNoValue.setBorderWidthRight(0);
                itemNoValue.setColspan(2);
                details.addCell(itemNoValue);

                PdfPCell projectNoValue = new PdfPCell(new Phrase(storageRecordDetail.getProjectNo(), fontEN));
//                projectNoValue.setBorder(0);
                projectNoValue.setBorderWidthTop(0);
                projectNoValue.setBorderWidthLeft(0);
                projectNoValue.setBorderWidthBottom(0);
                projectNoValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
                details.addCell(projectNoValue);

                PdfPCell priceAmountValue = new PdfPCell(new Phrase(storageRecordDetail.getPriceAmount().toString(), fontEN));
//                priceAmountValue.setBorder(0);
                priceAmountValue.setBorderWidthTop(0);
                priceAmountValue.setBorderWidthLeft(0);
                priceAmountValue.setBorderWidthBottom(0);
                priceAmountValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
                details.addCell(priceAmountValue);

                PdfPCell arriveAmountBackValue = new PdfPCell(new Phrase(storageRecordDetail.getValidDate()==null?"":storageRecordDetail.getValidDate().toString().toString(), fontEN));
//                arriveAmountBackValue.setBorder(0);
                arriveAmountBackValue.setBorderWidthTop(0);
                arriveAmountBackValue.setBorderWidthLeft(0);
                arriveAmountBackValue.setBorderWidthBottom(0);
                arriveAmountBackValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
                details.addCell(arriveAmountBackValue);

                PdfPCell batchNoValue = new PdfPCell(new Phrase(storageRecordDetail.getBatchNo(), fontEN));
//              batchNoValue.setBorder(0);
                batchNoValue.setBorderWidthTop(0);
                batchNoValue.setBorderWidthBottom(0);
                batchNoValue.setBorderWidthLeft(0);
                details.addCell(batchNoValue);

                details.completeRow();
                //第一行结束
 
                PdfPCell itemDescribeValue = new PdfPCell(new Phrase(storageRecordDetail.getItemName(), fontCN));
//              itemDescribeValue.setBorder(0);
                itemDescribeValue.setBorderWidthTop(0);
                itemDescribeValue.setBorderWidthLeft(0);
                itemDescribeValue.setBorderWidthBottom(0);
                itemDescribeValue.setColspan(3);
                details.addCell(itemDescribeValue);

                PdfPCell pieceQuantityValue = new PdfPCell(new Phrase(storageRecordDetail.getPieceQuantity().toString(), fontEN));
//                pieceQuantityValue.setBorder(0);
                pieceQuantityValue.setBorderWidthTop(0);
                pieceQuantityValue.setBorderWidthLeft(0);
                pieceQuantityValue.setBorderWidthBottom(0);
                pieceQuantityValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
                details.addCell(pieceQuantityValue);

              PdfPCell orderAmountOldsValue = new PdfPCell(new Phrase(storageRecordDetail.getCheckoutAgainDate()==null?"":storageRecordDetail.getCheckoutAgainDate().toString(), fontEN));
//              orderAmountOldsValue.setBorder(0);
              orderAmountOldsValue.setBorderWidthTop(0);
              orderAmountOldsValue.setBorderWidthLeft(0);
              orderAmountOldsValue.setBorderWidthBottom(0);
              orderAmountOldsValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
              details.addCell(orderAmountOldsValue);

              PdfPCell tbatchDescribeValue = new PdfPCell(new Phrase(storageRecordDetail.getBatchDescribe(), fontCN));
//              tbatchDescribeValue.setBorder(0);
              tbatchDescribeValue.setBorderWidthTop(0);
              tbatchDescribeValue.setBorderWidthLeft(0);
              tbatchDescribeValue.setBorderWidthBottom(0);
              tbatchDescribeValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
              details.addCell(tbatchDescribeValue);

              details.completeRow();
              //第二行结束

              PdfPCell itemPropertyValue = new PdfPCell(new Phrase(storageRecordDetail.getItemProperty(), fontCN));
//              itemPropertyValue.setBorder(0);
              itemPropertyValue.setBorderWidthTop(0);
              itemPropertyValue.setBorderWidthLeft(0);
              itemPropertyValue.setBorderWidthBottom(0);
              itemPropertyValue.setBorderWidthRight(0);
              itemPropertyValue.setColspan(2);
              details.addCell(itemPropertyValue);

              PdfPCell unitNameValue = new PdfPCell(new Phrase(storageRecordDetail.getUnitName(), fontCN));
//              unitNameValue.setBorder(0);
              unitNameValue.setBorderWidthTop(0);
              unitNameValue.setBorderWidthLeft(0);
              unitNameValue.setBorderWidthBottom(0);
              unitNameValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
              details.addCell(unitNameValue);

              PdfPCell itemPriceValue = new PdfPCell(new Phrase("", fontEN));
//              itemPriceValue.setBorder(0);
              itemPriceValue.setBorderWidthTop(0);
              itemPriceValue.setBorderWidthLeft(0);
              itemPriceValue.setBorderWidthBottom(0);
              itemPriceValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
              details.addCell(itemPriceValue);

              PdfPCell orderAmountTaxValue = new PdfPCell(new Phrase("", fontEN));
//              orderAmountTaxValue.setBorder(0);
              orderAmountTaxValue.setBorderWidthTop(0);
              orderAmountTaxValue.setBorderWidthLeft(0);
              orderAmountTaxValue.setBorderWidthBottom(0);
              orderAmountTaxValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
              details.addCell(orderAmountTaxValue);

              PdfPCell commentssValue = new PdfPCell(new Phrase(storageRecordDetail.getComments(), fontCN));
//              commentssValue.setBorder(0);
              commentssValue.setBorderWidthTop(0);
              commentssValue.setBorderWidthLeft(0);
              commentssValue.setRowspan(2);
              details.addCell(commentssValue);

              details.completeRow();
              //第三行结束
              

              PdfPCell floorNoValue = new PdfPCell(new Phrase(storageRecordDetail.getFloorNo(), fontCN));
//              floorNoValue.setBorder(0);
              floorNoValue.setBorderWidthTop(0);
              floorNoValue.setBorderWidthLeft(0);
              floorNoValue.setBorderWidthRight(0);
              floorNoValue.setColspan(2);
              details.addCell(floorNoValue);

              PdfPCell storageNoValue = new PdfPCell(new Phrase(storageRecordDetail.getStorageNo(), fontEN));
//              storageNoValue.setBorder(0);
              storageNoValue.setBorderWidthTop(0);
              storageNoValue.setBorderWidthLeft(0);
              storageNoValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
              details.addCell(storageNoValue);

              PdfPCell orderAmountValue = new PdfPCell(new Phrase("", fontEN));
//              orderAmountValue.setBorder(0);
              orderAmountValue.setBorderWidthTop(0);
              orderAmountValue.setBorderWidthLeft(0);
              orderAmountValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
              details.addCell(orderAmountValue);

              PdfPCell orderAmountTotalValue = new PdfPCell(new Phrase("", fontEN));
//              orderAmountTotalValue.setBorder(0);
              orderAmountTotalValue.setBorderWidthTop(0);
              orderAmountTotalValue.setBorderWidthLeft(0);
              orderAmountTotalValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
              details.addCell(orderAmountTotalValue);

              details.completeRow();
              //第四行结束
              
            }
            
            doc.add(details);
      	
        }
        ////////////////////////////////////////////////////////////////////////////////////////////
        
//	    doc.add(line);

	    
        PdfPTable masterFoot = new PdfPTable(8);
        
        masterFoot.setTotalWidth(new float[]{45, 85, 45, 85, 45, 85, 45, 85});
        masterFoot.setLockedWidth(true);
//        masterFoot.setSpacingBefore(10);

        PdfPCell detailsCountCell = new PdfPCell(new Phrase("笔数:", fontCN));
//        detailsCountCell.setBorder(0);
        detailsCountCell.setBorderWidthTop(0);
        detailsCountCell.setBorderWidthBottom(0);
        detailsCountCell.setBorderWidthRight(0);
        masterFoot.addCell(detailsCountCell);

        PdfPCell detailsCountValue = new PdfPCell(new Phrase(String.valueOf(storageRecord.getDetailsCount()), fontEN));
        detailsCountValue.setBorderWidthTop(0);
        detailsCountValue.setBorderWidthLeft(0);
        detailsCountValue.setBorderWidthBottom(0);
        detailsCountValue.setColspan(7);
        masterFoot.addCell(detailsCountValue);

        //第一行结束
        masterFoot.completeRow();

        PdfPCell itemAmountCell = new PdfPCell(new Phrase("数量合计:", fontCN));
//        itemAmountCell.setBorder(0);
        itemAmountCell.setBorderWidthTop(0);
        itemAmountCell.setBorderWidthRight(0);
        masterFoot.addCell(itemAmountCell);

        PdfPCell itemAmountValue = new PdfPCell(new Phrase(storageRecord.getItemAmount().toString(), fontEN));
        itemAmountValue.setBorderWidthTop(0);
        itemAmountValue.setBorderWidthLeft(0);
        itemAmountValue.setColspan(7);
        masterFoot.addCell(itemAmountValue);


        //第二行结束
        masterFoot.completeRow();


        doc.add(masterFoot);
        
        
        
	    
        PdfPTable masterTail = new PdfPTable(8);
        
        masterTail.setTotalWidth(new float[]{45, 65, 45, 105, 45, 65, 45, 105});
        masterTail.setLockedWidth(true);
        masterTail.setSpacingBefore(10);

        PdfPCell cUsernameCell = new PdfPCell(new Phrase("制单:", fontCN));
        cUsernameCell.setBorder(0);
        masterTail.addCell(cUsernameCell);

        PdfPCell cUsernameValue = new PdfPCell(new Phrase(storageRecord.getcUsername(), fontCN));
        cUsernameValue.setBorder(0);
        masterTail.addCell(cUsernameValue);

        PdfPCell cDatetimeCell = new PdfPCell(new Phrase("制单时间:", fontCN));
        cDatetimeCell.setBorder(0);
        masterTail.addCell(cDatetimeCell);

        PdfPCell cDatetimeValue = new PdfPCell(new Phrase(storageRecord.getcDatetime().toString(), fontEN));
        cDatetimeValue.setBorder(0);
        masterTail.addCell(cDatetimeValue);

        PdfPCell tUsernameCell = new PdfPCell(new Phrase("审核:", fontCN));
        tUsernameCell.setBorder(0);
        masterTail.addCell(tUsernameCell);

        PdfPCell tUsernameValue = new PdfPCell(new Phrase(storageRecord.gettUsername(), fontCN));
        tUsernameValue.setBorder(0);
        masterTail.addCell(tUsernameValue);

        PdfPCell tDatetimeCell = new PdfPCell(new Phrase("审核时间:", fontCN));
        tDatetimeCell.setBorder(0);
        masterTail.addCell(tDatetimeCell);

        PdfPCell tDatetimeValue = new PdfPCell(new Phrase(storageRecord.gettDatetime()==null?"":storageRecord.gettDatetime().toString(), fontEN));
        tDatetimeValue.setBorder(0);
        masterTail.addCell(tDatetimeValue);


        masterTail.completeRow();
        

        doc.add(masterTail);
	    
        Chunk printTimeChunk = new Chunk("打印时间: ",fontCN);
        String printTime = Utils.getCurrentDateTime().toString();
        Paragraph printTimeParagraph = new Paragraph(printTimeChunk);
        Chunk printTimeValueChunk = new Chunk(printTime,fontEN);
        printTimeParagraph.add(printTimeValueChunk);
        printTimeParagraph.setAlignment(Element.ALIGN_RIGHT);
	    doc.add(printTimeParagraph);

	    
//	    doc.close();
	    
	    
	    
//        int pageNumber = doc.getPageNumber();
//        System.out.println(pageNumber);
//	    Rectangle rect = doc.getPageSize();
//	    System.out.println("rect.getHeight()-->"+rect.getHeight());
//	    System.out.println("rect.getWidth()-->"+rect.getWidth());
//	    System.out.println("rect.getLeft()-->"+rect.getLeft());
//	    System.out.println("rect.getTop()-->"+rect.getTop());
//	    System.out.println("rect.getBottom()-->"+rect.getBottom());
//	    System.out.println("rect.getRight()-->"+rect.getRight());
//	    System.out.println("rect.getBorder()-->"+rect.getBorder());
//	    System.out.println("rect.getBorderWidth()-->"+rect.getBorderWidth());
//	    System.out.println("rect.getBorderWidthTop()-->"+rect.getBorderWidthTop());
//	    System.out.println("rect.getBorderWidthLeft()-->"+rect.getBorderWidthLeft());
//	    System.out.println("rect.getBorderWidthBottom()-->"+rect.getBorderWidthBottom());
//	    System.out.println("rect.getBorderWidthRight()-->"+rect.getBorderWidthRight());

	}

	
	//盘点单打印
	@Override
	public void invPDDJPrintPDF(String fID, Document doc) throws Exception {
		
//	@Test
//	public void storageRecordPrintPDF() throws Exception {
//		System.out.println("fID-->"+id);
		
//	    Document doc = new Document();// 创建一个PDF文档，我们的PDF内容都写在上面
	    
//	    PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(new File("c://pdftest//storageRecord.pdf"))); // 将pdf文档写入文件

//		String fID = "bf61ec2bc8163a3ad3d8572ad2fee7c6";
		StorageRecord storageRecord = storageRecordService.getByID(fID);
	   
//	    response.setContentType("application/pdf");
//	    PdfWriter.getInstance(doc, response.getOutputStream());
//	    
//	    doc.open();
	    
	    Font fontEN = new Font(BaseFont.createFont(),9);
	    BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);  	    
//	    Font font = new Font(baseFont, 10, Font.ITALIC);
	    Font fontCN = new Font(baseFont, 9);
	    Paragraph pEnterpriseName = new Paragraph(storageRecord.getEnterpriseName(),fontCN);
	    // 居中显示
	    pEnterpriseName.setAlignment(Element.ALIGN_CENTER);
	    pEnterpriseName.setSpacingAfter(-10);
	    Paragraph pBillTypeName = new Paragraph(storageRecord.getBillTypeName(),new Font(baseFont,20));
	    // 居中显示
	    pBillTypeName.setAlignment(Element.ALIGN_CENTER);
	    LineSeparator line = new LineSeparator(1f, 100, BaseColor.BLACK, Element.ALIGN_CENTER, -5f);

	    
	    
	    
	    
	    
	    doc.add(pEnterpriseName);
	    doc.add(pBillTypeName);
	    doc.add(line);
	    
	    
        PdfPTable masterHead = new PdfPTable(8);
        
//        masterHead.setTotalWidth(new float[]{60, 200, 60, 200});
        masterHead.setTotalWidth(new float[]{45, 85, 45, 85, 45, 85, 45, 85});
        masterHead.setLockedWidth(true);
        masterHead.setSpacingBefore(10);
        
        PdfPCell ordrDateCell = new PdfPCell(new Phrase("单据日期:", fontCN));
        ordrDateCell.setUseBorderPadding(true);
        //
        // Setting cell's border width and color
        //
        ordrDateCell.setBorderWidth(0f);
//        ordrDateCell.setBorderColor(BaseColor.BLUE);
        masterHead.addCell(ordrDateCell);

        PdfPCell ordrDateValue = new PdfPCell(new Phrase(storageRecord.getOrderDate().toString(), fontEN));
        ordrDateValue.setUseBorderPadding(true);
        ordrDateValue.setBorderWidth(0f);
        //
        // Setting cell's background color
        //
//        cell2.setBackgroundColor(BaseColor.GRAY);
        //
        // Setting cell's individual border color
        //
//        cell2.setBorderWidthTop(1f);
//        cell2.setBorderColorTop(BaseColor.RED);
//        cell2.setBorderColorRight(BaseColor.GREEN);
//        cell2.setBorderColorBottom(BaseColor.BLUE);
//        cell2.setBorderColorLeft(BaseColor.BLACK);
        masterHead.addCell(ordrDateValue);

        PdfPCell auditCell = new PdfPCell(new Phrase("单据状态:", fontCN));
        auditCell.setUseBorderPadding(true);
        auditCell.setBorderWidth(0f);
        //
        // Setting cell's individual border width
        //
//        cell3.setBorderWidthTop(2f);
//        cell3.setBorderWidthRight(1f);
//        cell3.setBorderWidthBottom(2f);
//        cell3.setBorderWidthLeft(1f);
        masterHead.addCell(auditCell);

        String auditStatus = "待审核";
        String audit = storageRecord.getAudit();
        String state = storageRecord.getState();
        if(audit.equals("confirm")){
        	auditStatus = "已审核";
        }else if(audit.equals("active") && state.equals("confirm")){
        	auditStatus = "审核中";
        }else{
        	auditStatus = "待审核";
        }
        
       PdfPCell auditValue = new PdfPCell(new Phrase(auditStatus, fontCN));
       auditValue.setUseBorderPadding(true);
       auditValue.setBorderWidth(0f);
        //
        // Setting cell's individual border width
        //
//        cell4.setBorderWidthTop(2f);
//        cell4.setBorderWidthRight(1f);
//        cell4.setBorderWidthBottom(2f);
//        cell4.setBorderWidthLeft(1f);
        masterHead.addCell(auditValue);
        
        PdfPCell employeeNameCell = new PdfPCell(new Phrase("经办人:", fontCN));
        employeeNameCell.setBorder(0);
        masterHead.addCell(employeeNameCell);
        PdfPCell employeeNameValue = new PdfPCell(new Phrase(storageRecord.getEmployeeName(), fontCN));
        employeeNameValue.setBorder(0);
        employeeNameValue.setColspan(3);
        masterHead.addCell(employeeNameValue);
         

        //第一行结束
        masterHead.completeRow();
        
        PdfPCell orderNoCell = new PdfPCell(new PdfPCell(new Phrase("单号:", fontCN)));
        orderNoCell.setBorder(0);
        masterHead.addCell(orderNoCell);
        PdfPCell orderNoValue = new PdfPCell(new PdfPCell(new Phrase(storageRecord.getRecordNo(), fontEN)));
        orderNoValue.setBorder(0);
        orderNoValue.setColspan(7);
        masterHead.addCell(orderNoValue);
        
        //第二行结束
        masterHead.completeRow();
       
        
        PdfPCell commentsCell = new PdfPCell(new Phrase("备注:", fontCN));
        commentsCell.setBorder(0);
        masterHead.addCell(commentsCell);
        PdfPCell commentsValue = new PdfPCell(new Phrase(storageRecord.getComments(), fontCN));
        commentsValue.setBorder(0);
        commentsValue.setColspan(7);
        masterHead.addCell(commentsValue);
        
        //第n行结束
        masterHead.completeRow();

        doc.add(masterHead);
//	    doc.add(line);
	    

        /*
        Image image = Image.getInstance("c://pdftest//smp.png");

        image.setAlignment(Image.ALIGN_RIGHT);
        // 设置边框
        image.setBorder(Image.BOX);
        image.setBorderWidth(2);
        image.setBorderColor(BaseColor.RED);
        // 设置图片大小
        
//        ScaleToFit有两个参数，指的是长和宽的最大值，但是图片的长宽比还是不会变的
//        ScaleAbsoluteHeight设置图片的高度，不管长宽比 ScaleAbsoluteWidth设置图片的宽度，不管长宽比
//        ScalePercent等比例缩放
        
//         image.scaleToFit(100, 100);
//         image.scaleAbsoluteHeight(100f);
//         image.scaleAbsoluteWidth(100f);

        image.scalePercent(50f);
        // 图片旋转30度
        image.setRotationDegrees(30);

        doc.add(image);
        */
        
        
        
        
        
	    //////////////////////////////////////////////////////////////////////////////////////////
	    
        PdfPTable details = new PdfPTable(7);
        details.setTotalWidth(new float[]{15, 70, 70, 80, 75, 75, 135});//520
        details.setLockedWidth(true);
        details.setSpacingBefore(10);

        PdfPCell sharpCell = new PdfPCell(new Phrase("序号", fontCN));
//        sharpCell.setBorder(0);
        sharpCell.setRowspan(4);
        sharpCell.setHorizontalAlignment(Element.ALIGN_CENTER);
        sharpCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        details.addCell(sharpCell);

        PdfPCell itemNoCell = new PdfPCell(new Phrase("物料编码", fontCN));
//        itemNoCell.setBorder(0);
//        itemNoCell.setBorderWidthTop(0);
        itemNoCell.setBorderWidthLeft(0);
        itemNoCell.setBorderWidthBottom(0);
        itemNoCell.setBorderWidthRight(0);
        itemNoCell.setColspan(2);
        details.addCell(itemNoCell);

        PdfPCell projectNoCell = new PdfPCell(new Phrase("项目号", fontCN));
//        projectNoCell.setBorder(0);
        projectNoCell.setBorderWidthLeft(0);
        projectNoCell.setBorderWidthBottom(0);
        projectNoCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(projectNoCell);

        PdfPCell priceAmountCell = new PdfPCell(new Phrase("账面数量", fontCN));
//        priceAmountCell.setBorder(0);
        priceAmountCell.setBorderWidthLeft(0);
        priceAmountCell.setBorderWidthBottom(0);
        priceAmountCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(priceAmountCell);

        PdfPCell arriveAmountBackCell = new PdfPCell(new Phrase("账面件数", fontCN));
//        arriveAmountBackCell.setBorder(0);
        arriveAmountBackCell.setBorderWidthLeft(0);
        arriveAmountBackCell.setBorderWidthBottom(0);
        arriveAmountBackCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(arriveAmountBackCell);

        PdfPCell batchNoCell = new PdfPCell(new Phrase("批号", fontCN));
//        batchNoCell.setBorder(0);
        batchNoCell.setBorderWidthLeft(0);
        batchNoCell.setBorderWidthBottom(0);
        details.addCell(batchNoCell);
        
        details.completeRow();
        //第一行结束

        PdfPCell itemDescribeCell = new PdfPCell(new Phrase("名称", fontCN));
//        itemDescribeCell.setBorder(0);
        itemDescribeCell.setBorderWidthTop(0);
        itemDescribeCell.setBorderWidthLeft(0);
        itemDescribeCell.setBorderWidthBottom(0);
        itemDescribeCell.setColspan(3);
        details.addCell(itemDescribeCell);

        PdfPCell pieceQuantityCell = new PdfPCell(new Phrase("盘点数量", fontCN));
//        pieceQuantityCell.setBorder(0);
        pieceQuantityCell.setBorderWidthTop(0);
        pieceQuantityCell.setBorderWidthLeft(0);
        pieceQuantityCell.setBorderWidthBottom(0);
        pieceQuantityCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(pieceQuantityCell);

        PdfPCell orderAmountOldsCell = new PdfPCell(new Phrase("盘点件数", fontCN));
//        orderAmountOldsCell.setBorder(0);
        orderAmountOldsCell.setBorderWidthTop(0);
        orderAmountOldsCell.setBorderWidthLeft(0);
        orderAmountOldsCell.setBorderWidthBottom(0);
        orderAmountOldsCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(orderAmountOldsCell);

        PdfPCell batchDescribeCell = new PdfPCell(new Phrase("批号说明", fontCN));
//        batchDescribeCell.setBorder(0);
        batchDescribeCell.setBorderWidthTop(0);
        batchDescribeCell.setBorderWidthLeft(0);
        batchDescribeCell.setBorderWidthBottom(0);
        details.addCell(batchDescribeCell);

        details.completeRow();
        //第二行结束

        PdfPCell itemPropertyCell = new PdfPCell(new Phrase("规格", fontCN));
//        itemPropertyCell.setBorder(0);
        itemPropertyCell.setBorderWidthTop(0);
        itemPropertyCell.setBorderWidthLeft(0);
        itemPropertyCell.setBorderWidthBottom(0);
        itemPropertyCell.setBorderWidthRight(0);
        itemPropertyCell.setColspan(2);
        details.addCell(itemPropertyCell);

        PdfPCell unitNameCell = new PdfPCell(new Phrase("单位", fontCN));
//        unitNameCell.setBorder(0);
        unitNameCell.setBorderWidthTop(0);
        unitNameCell.setBorderWidthLeft(0);
        unitNameCell.setBorderWidthBottom(0);
        unitNameCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(unitNameCell);

        PdfPCell itemPriceCell = new PdfPCell(new Phrase("差异数量", fontCN));
//        itemPriceCell.setBorder(0);
        itemPriceCell.setBorderWidthTop(0);
        itemPriceCell.setBorderWidthLeft(0);
        itemPriceCell.setBorderWidthBottom(0);
        itemPriceCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(itemPriceCell);

        PdfPCell orderAmountTaxsCell = new PdfPCell(new Phrase("差异件数", fontCN));
//        orderAmountTaxsCell.setBorder(0);
        orderAmountTaxsCell.setBorderWidthTop(0);
        orderAmountTaxsCell.setBorderWidthLeft(0);
        orderAmountTaxsCell.setBorderWidthBottom(0);
        orderAmountTaxsCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(orderAmountTaxsCell);

        PdfPCell commentssCell = new PdfPCell(new Phrase("备注", fontCN));
//        commentssCell.setBorder(0);
        commentssCell.setBorderWidthTop(0);
        commentssCell.setBorderWidthLeft(0);
        commentssCell.setRowspan(2);
        details.addCell(commentssCell);

        details.completeRow();
        //第三行结束

        PdfPCell floorNoCell = new PdfPCell(new Phrase("库存地", fontCN));
//        floorNoCell.setBorder(0);
        floorNoCell.setBorderWidthTop(0);
        floorNoCell.setBorderWidthLeft(0);
        floorNoCell.setBorderWidthRight(0);
        floorNoCell.setColspan(2);
        details.addCell(floorNoCell);

        PdfPCell storageNoCell = new PdfPCell(new Phrase("仓库编码", fontCN));
//        storageNoCell.setBorder(0);
        storageNoCell.setBorderWidthTop(0);
        storageNoCell.setBorderWidthLeft(0);
        storageNoCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(storageNoCell);

        PdfPCell orderAmountCell = new PdfPCell(new Phrase("有效日期", fontCN));
//        orderAmountCell.setBorder(0);
        orderAmountCell.setBorderWidthTop(0);
        orderAmountCell.setBorderWidthLeft(0);
        orderAmountCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(orderAmountCell);

        PdfPCell orderAmountTotalsCell = new PdfPCell(new Phrase("复检日期", fontCN));
//        orderAmountTotalsCell.setBorder(0);
        orderAmountTotalsCell.setBorderWidthTop(0);
        orderAmountTotalsCell.setBorderWidthLeft(0);
        orderAmountTotalsCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        details.addCell(orderAmountTotalsCell);

        details.completeRow();
        //第四行结束
        
        
//        doc.add(details);
        
        ////////////////////////////////////////////////////////////////////////////////////////////
        
        
	    //////////////////////////////////////////////////////////////////////////////////////////
        List<StorageRecordDetail> storageRecordDetails = storageRecordDetailService.getByMasterID(fID);
        if(storageRecordDetails.size()>0){
    	    
//            PdfPTable detailsValue = new PdfPTable(8);
//            
//            detailsValue.setTotalWidth(new float[]{20, 70, 70, 80, 80, 80, 60, 60});//520
//            detailsValue.setLockedWidth(true);
//            detailsValue.setSpacingBefore(10);
            
            for(int i=0;i<storageRecordDetails.size();i++){
            	StorageRecordDetail storageRecordDetail = storageRecordDetails.get(i);

            	//序号
            	String rowNo = String.valueOf(i+1);
                PdfPCell sharpValue = new PdfPCell(new Phrase(rowNo, fontEN));
//                sharpValue.setBorder(0);
                sharpValue.setBorderWidthTop(0);
                sharpValue.setRowspan(4);
                sharpValue.setHorizontalAlignment(Element.ALIGN_CENTER);
                sharpValue.setVerticalAlignment(Element.ALIGN_MIDDLE);
                details.addCell(sharpValue);

                PdfPCell itemNoValue = new PdfPCell(new Phrase(storageRecordDetail.getItemNo(), fontEN));
//                itemNoValue.setBorder(0);
                itemNoValue.setBorderWidthTop(0);
                itemNoValue.setBorderWidthLeft(0);
                itemNoValue.setBorderWidthBottom(0);
                itemNoValue.setBorderWidthRight(0);
                itemNoValue.setColspan(2);
                details.addCell(itemNoValue);

                PdfPCell projectNoValue = new PdfPCell(new Phrase(storageRecordDetail.getProjectNo(), fontEN));
//                projectNoValue.setBorder(0);
                projectNoValue.setBorderWidthTop(0);
                projectNoValue.setBorderWidthLeft(0);
                projectNoValue.setBorderWidthBottom(0);
                projectNoValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
                details.addCell(projectNoValue);

                PdfPCell priceAmountValue = new PdfPCell(new Phrase(storageRecordDetail.getInvoiceQuantityIng().toString(), fontEN));
//                priceAmountValue.setBorder(0);
                priceAmountValue.setBorderWidthTop(0);
                priceAmountValue.setBorderWidthLeft(0);
                priceAmountValue.setBorderWidthBottom(0);
                priceAmountValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
                details.addCell(priceAmountValue);

                PdfPCell arriveAmountBackValue = new PdfPCell(new Phrase(storageRecordDetail.getEvaluateQuantityIng().toString(), fontEN));
//                arriveAmountBackValue.setBorder(0);
                arriveAmountBackValue.setBorderWidthTop(0);
                arriveAmountBackValue.setBorderWidthLeft(0);
                arriveAmountBackValue.setBorderWidthBottom(0);
                arriveAmountBackValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
                details.addCell(arriveAmountBackValue);

                PdfPCell batchNoValue = new PdfPCell(new Phrase(storageRecordDetail.getBatchNo(), fontEN));
//              batchNoValue.setBorder(0);
                batchNoValue.setBorderWidthTop(0);
                batchNoValue.setBorderWidthBottom(0);
                batchNoValue.setBorderWidthLeft(0);
                details.addCell(batchNoValue);

                details.completeRow();
                //第一行结束
 
                PdfPCell itemDescribeValue = new PdfPCell(new Phrase(storageRecordDetail.getItemName(), fontCN));
//              itemDescribeValue.setBorder(0);
                itemDescribeValue.setBorderWidthTop(0);
                itemDescribeValue.setBorderWidthLeft(0);
                itemDescribeValue.setBorderWidthBottom(0);
                itemDescribeValue.setColspan(3);
                details.addCell(itemDescribeValue);

                PdfPCell pieceQuantityValue = new PdfPCell(new Phrase(storageRecordDetail.getInvoiceQuantity().toString(), fontEN));
//                pieceQuantityValue.setBorder(0);
                pieceQuantityValue.setBorderWidthTop(0);
                pieceQuantityValue.setBorderWidthLeft(0);
                pieceQuantityValue.setBorderWidthBottom(0);
                pieceQuantityValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
                details.addCell(pieceQuantityValue);

              PdfPCell orderAmountOldsValue = new PdfPCell(new Phrase(storageRecordDetail.getEvaluateQuantity().toString(), fontEN));
//              orderAmountOldsValue.setBorder(0);
              orderAmountOldsValue.setBorderWidthTop(0);
              orderAmountOldsValue.setBorderWidthLeft(0);
              orderAmountOldsValue.setBorderWidthBottom(0);
              orderAmountOldsValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
              details.addCell(orderAmountOldsValue);

              PdfPCell tbatchDescribeValue = new PdfPCell(new Phrase(storageRecordDetail.getBatchDescribe(), fontCN));
//              tbatchDescribeValue.setBorder(0);
              tbatchDescribeValue.setBorderWidthTop(0);
              tbatchDescribeValue.setBorderWidthLeft(0);
              tbatchDescribeValue.setBorderWidthBottom(0);
              tbatchDescribeValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
              details.addCell(tbatchDescribeValue);

              details.completeRow();
              //第二行结束

              PdfPCell itemPropertyValue = new PdfPCell(new Phrase(storageRecordDetail.getItemProperty(), fontCN));
//              itemPropertyValue.setBorder(0);
              itemPropertyValue.setBorderWidthTop(0);
              itemPropertyValue.setBorderWidthLeft(0);
              itemPropertyValue.setBorderWidthBottom(0);
              itemPropertyValue.setBorderWidthRight(0);
              itemPropertyValue.setColspan(2);
              details.addCell(itemPropertyValue);

              PdfPCell unitNameValue = new PdfPCell(new Phrase(storageRecordDetail.getUnitName(), fontCN));
//              unitNameValue.setBorder(0);
              unitNameValue.setBorderWidthTop(0);
              unitNameValue.setBorderWidthLeft(0);
              unitNameValue.setBorderWidthBottom(0);
              unitNameValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
              details.addCell(unitNameValue);

              PdfPCell itemPriceValue = new PdfPCell(new Phrase("", fontEN));
//              itemPriceValue.setBorder(0);
              itemPriceValue.setBorderWidthTop(0);
              itemPriceValue.setBorderWidthLeft(0);
              itemPriceValue.setBorderWidthBottom(0);
              itemPriceValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
              details.addCell(itemPriceValue);

              PdfPCell orderAmountTaxValue = new PdfPCell(new Phrase("", fontEN));
//              orderAmountTaxValue.setBorder(0);
              orderAmountTaxValue.setBorderWidthTop(0);
              orderAmountTaxValue.setBorderWidthLeft(0);
              orderAmountTaxValue.setBorderWidthBottom(0);
              orderAmountTaxValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
              details.addCell(orderAmountTaxValue);

              PdfPCell commentssValue = new PdfPCell(new Phrase(storageRecordDetail.getComments(), fontCN));
//              commentssValue.setBorder(0);
              commentssValue.setBorderWidthTop(0);
              commentssValue.setBorderWidthLeft(0);
              commentssValue.setRowspan(2);
              details.addCell(commentssValue);

              details.completeRow();
              //第三行结束
              

              PdfPCell floorNoValue = new PdfPCell(new Phrase(storageRecordDetail.getFloorNo(), fontCN));
//              floorNoValue.setBorder(0);
              floorNoValue.setBorderWidthTop(0);
              floorNoValue.setBorderWidthLeft(0);
              floorNoValue.setBorderWidthRight(0);
              floorNoValue.setColspan(2);
              details.addCell(floorNoValue);

              PdfPCell storageNoValue = new PdfPCell(new Phrase(storageRecordDetail.getStorageNo(), fontEN));
//              storageNoValue.setBorder(0);
              storageNoValue.setBorderWidthTop(0);
              storageNoValue.setBorderWidthLeft(0);
              storageNoValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
              details.addCell(storageNoValue);

              PdfPCell orderAmountValue = new PdfPCell(new Phrase(storageRecordDetail.getValidDate()==null?"":storageRecordDetail.getValidDate().toString(), fontEN));
//              orderAmountValue.setBorder(0);
              orderAmountValue.setBorderWidthTop(0);
              orderAmountValue.setBorderWidthLeft(0);
              orderAmountValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
              details.addCell(orderAmountValue);

              PdfPCell orderAmountTotalValue = new PdfPCell(new Phrase(storageRecordDetail.getCheckoutAgainDate()==null?"":storageRecordDetail.getCheckoutAgainDate().toString(), fontEN));
//              orderAmountTotalValue.setBorder(0);
              orderAmountTotalValue.setBorderWidthTop(0);
              orderAmountTotalValue.setBorderWidthLeft(0);
              orderAmountTotalValue.setHorizontalAlignment(Element.ALIGN_RIGHT);
              details.addCell(orderAmountTotalValue);

              details.completeRow();
              //第四行结束
              
            }
            
            doc.add(details);
      	
        }
        ////////////////////////////////////////////////////////////////////////////////////////////
        
//	    doc.add(line);

	    
        PdfPTable masterFoot = new PdfPTable(8);
        
        masterFoot.setTotalWidth(new float[]{45, 85, 45, 85, 45, 85, 45, 85});
        masterFoot.setLockedWidth(true);
//        masterFoot.setSpacingBefore(10);

        PdfPCell detailsCountCell = new PdfPCell(new Phrase("笔数:", fontCN));
//        detailsCountCell.setBorder(0);
        detailsCountCell.setBorderWidthTop(0);
        detailsCountCell.setBorderWidthBottom(0);
        detailsCountCell.setBorderWidthRight(0);
        masterFoot.addCell(detailsCountCell);

        PdfPCell detailsCountValue = new PdfPCell(new Phrase(String.valueOf(storageRecord.getDetailsCount()), fontEN));
        detailsCountValue.setBorderWidthTop(0);
        detailsCountValue.setBorderWidthLeft(0);
        detailsCountValue.setBorderWidthBottom(0);
        detailsCountValue.setColspan(7);
        masterFoot.addCell(detailsCountValue);

        //第一行结束
        masterFoot.completeRow();

        PdfPCell itemAmountCell = new PdfPCell(new Phrase("数量合计:", fontCN));
//        itemAmountCell.setBorder(0);
        itemAmountCell.setBorderWidthTop(0);
        itemAmountCell.setBorderWidthRight(0);
        masterFoot.addCell(itemAmountCell);

        PdfPCell itemAmountValue = new PdfPCell(new Phrase(storageRecord.getItemAmount().toString(), fontEN));
        itemAmountValue.setBorderWidthTop(0);
        itemAmountValue.setBorderWidthLeft(0);
        itemAmountValue.setColspan(7);
        masterFoot.addCell(itemAmountValue);


        //第二行结束
        masterFoot.completeRow();


        doc.add(masterFoot);
        
        
        
	    
        PdfPTable masterTail = new PdfPTable(8);
        
        masterTail.setTotalWidth(new float[]{45, 65, 45, 105, 45, 65, 45, 105});
        masterTail.setLockedWidth(true);
        masterTail.setSpacingBefore(10);

        PdfPCell cUsernameCell = new PdfPCell(new Phrase("制单:", fontCN));
        cUsernameCell.setBorder(0);
        masterTail.addCell(cUsernameCell);

        PdfPCell cUsernameValue = new PdfPCell(new Phrase(storageRecord.getcUsername(), fontCN));
        cUsernameValue.setBorder(0);
        masterTail.addCell(cUsernameValue);

        PdfPCell cDatetimeCell = new PdfPCell(new Phrase("制单时间:", fontCN));
        cDatetimeCell.setBorder(0);
        masterTail.addCell(cDatetimeCell);

        PdfPCell cDatetimeValue = new PdfPCell(new Phrase(storageRecord.getcDatetime().toString(), fontEN));
        cDatetimeValue.setBorder(0);
        masterTail.addCell(cDatetimeValue);

        PdfPCell tUsernameCell = new PdfPCell(new Phrase("审核:", fontCN));
        tUsernameCell.setBorder(0);
        masterTail.addCell(tUsernameCell);

        PdfPCell tUsernameValue = new PdfPCell(new Phrase(storageRecord.gettUsername(), fontCN));
        tUsernameValue.setBorder(0);
        masterTail.addCell(tUsernameValue);

        PdfPCell tDatetimeCell = new PdfPCell(new Phrase("审核时间:", fontCN));
        tDatetimeCell.setBorder(0);
        masterTail.addCell(tDatetimeCell);

        PdfPCell tDatetimeValue = new PdfPCell(new Phrase(storageRecord.gettDatetime()==null?"":storageRecord.gettDatetime().toString(), fontEN));
        tDatetimeValue.setBorder(0);
        masterTail.addCell(tDatetimeValue);


        masterTail.completeRow();
        

        doc.add(masterTail);
	    
        Chunk printTimeChunk = new Chunk("打印时间: ",fontCN);
        String printTime = Utils.getCurrentDateTime().toString();
        Paragraph printTimeParagraph = new Paragraph(printTimeChunk);
        Chunk printTimeValueChunk = new Chunk(printTime,fontEN);
        printTimeParagraph.add(printTimeValueChunk);
        printTimeParagraph.setAlignment(Element.ALIGN_RIGHT);
	    doc.add(printTimeParagraph);

	    
//	    doc.close();
	    
	    
	    
//        int pageNumber = doc.getPageNumber();
//        System.out.println(pageNumber);
//	    Rectangle rect = doc.getPageSize();
//	    System.out.println("rect.getHeight()-->"+rect.getHeight());
//	    System.out.println("rect.getWidth()-->"+rect.getWidth());
//	    System.out.println("rect.getLeft()-->"+rect.getLeft());
//	    System.out.println("rect.getTop()-->"+rect.getTop());
//	    System.out.println("rect.getBottom()-->"+rect.getBottom());
//	    System.out.println("rect.getRight()-->"+rect.getRight());
//	    System.out.println("rect.getBorder()-->"+rect.getBorder());
//	    System.out.println("rect.getBorderWidth()-->"+rect.getBorderWidth());
//	    System.out.println("rect.getBorderWidthTop()-->"+rect.getBorderWidthTop());
//	    System.out.println("rect.getBorderWidthLeft()-->"+rect.getBorderWidthLeft());
//	    System.out.println("rect.getBorderWidthBottom()-->"+rect.getBorderWidthBottom());
//	    System.out.println("rect.getBorderWidthRight()-->"+rect.getBorderWidthRight());

	}



	
	


	
	
	
	
	//TODO 获取物料信息
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageService#getItemInfo(java.lang.String, java.lang.String)
	 */
	/*
	@Override
	public Map<String,Object> getItemInfo(String itemID){
		FileItem fileItem=fileItemService.getByID(itemID);//new FileItem(itemNo,"");
		
		Map<String,Object> map =  new HashMap<String, Object>();
		
		String state = "success";
		if (fileItem == null ){
			state = "failure";
			System.out.println("系统提示-->物料档案不存在。");
		}else{
			map=fileItemService.toMap(fileItem);
		}
		map.put("state", state);
		
		return map;
	}
	*/

	

	/*
	//BOM档案
	@Override
	public JSONObject getBomInfo(String itemID) {
		
		JSONObject json = new JSONObject();
		
		//主件信息
		BomMain bomMain = bomMainService.getByNo(itemID);
		
		//元件列表
		//判断是否可以定制（是否存在BOM结构，并且含有配置项）
		//是否包含配置件标识
		int configCount = 0;
		JSONArray elements = new JSONArray();

		List<BomElement> elementList = bomElementService.getElements(itemID);
		for(BomElement bomElement: elementList) {
			//物料ID
			String elementItemID = bomElement.getElementItemID();
			//组合用量
			BigDecimal itemAmount = bomElement.getItemAmount();
			int dSelected = bomElement.getdSelected();
			
			FileItem fileItem = fileItemService.getByID(elementItemID);
			
			//////////////////////装配itemDescribe////////////////////////////
			String itemProperty = fileItem.getItemProperty();
			String itemDescribe = null;
			if(itemProperty==null) {
				itemDescribe = fileItem.getItemName();
			}else {
				itemDescribe = fileItem.getItemName() + "【" + itemProperty + "】";
			}
			fileItem.setItemDescribe(itemDescribe);
			/////////////////////////////////////////////////////////////////////
			
			if("C".equals(fileItem.getProcess())) {
				configCount++;
			}
			
			JSONObject item = (JSONObject) JSON.toJSON(fileItem);
			
			//写入组合用量
			item.put("itemAmount", itemAmount);
			item.put("dSelected", dSelected);

			elements.add(item);
		}
		
		//构建data
		JSONObject data = (JSONObject) JSON.toJSON(bomMain);
		data.put("configCount", configCount);
		data.put("elements", elements);
		
		json.put("data", data);
		json.put("code", 0);
		json.put("msg", "success");
		
		return json;
	}
	*/


	//TODO 获取物料信息
		/* (non-Javadoc)
		 * @see com.iune.erp.inventory.IStorageService#getItemInfo(java.lang.String, java.lang.String)
		 */
		/*
		@Override
		public Map<String,Object> getItemInfo(String itemID){
			FileItem fileItem=fileItemService.getByID(itemID);//new FileItem(itemNo,"");
			
			Map<String,Object> map =  new HashMap<String, Object>();
			
			String state = "success";
			if (fileItem == null ){
				state = "failure";
				System.out.println("系统提示-->物料档案不存在。");
			}else{
				map=fileItemService.toMap(fileItem);
			}
			map.put("state", state);
			
			return map;
		}
		*/
	
		
	
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageService#getItemInfoByName(java.lang.String, java.lang.String, java.lang.String)
	 */
	/*
	@Override
	public Map<String,Object> getItemInfoByName(String itemName, String enterpriseNo){
//		FileItemUtil fiu = new FileItemUtil();
		FileItem fileItem=fileItemService.getByName(itemName, enterpriseNo);//new FileItem(itemDescribe,rationSize,"");
		return getItemInfo(fileItem.getfID());
	}
	*/

	
	//获取批号信息
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageService#getBatchNoInfo(java.lang.String, java.lang.String, java.lang.String)
	 */
	@Override
	public Map<String,Object> getBatchNoInfo(String itemID,String batchNo,String enterpriseNo){
		Map<String,Object> map =  new HashMap<String, Object>();
		
//		ItemBatchUtil ibu = new ItemBatchUtil();
		ItemBatch itemBatch = itemBatchService.getByNo(itemID, batchNo, enterpriseNo);
		
		if (null == itemBatch.getfID() || "".equals(itemBatch.getfID())){
			map.put("state", "failure");
		}else{
			map = itemBatchService.toMap(itemBatch);
		}
		
		return map;
	}
	
	
	
	
	
	////////////////////////////////////////////////////////////////////////////////////////
	

	//退库通用函数
	@Transactional
	@Override
	public StorageRecord storageRecordBACKInsert(StorageRecord storageSource
			,String cUsercode,String cUsername,String userId,String autoState/*自动提交*/, int flowType, String autoPayment/*现结*/,String employeeNo,String employeeName){
		
		if(storageSource==null){
			//源单据不存在
			return null;
		}
		
		String billType = null;
		//销售退货单
		if(storageSource.getBillType().equals("XSCK")){
			billType = "XSRK";//销售退货单
		}
		//采购退货单
		if(storageSource.getBillType().equals("CGRK")){
			billType = "CGCK";//销售退货单
		}
		//生产退库
		if(storageSource.getBillType().equals("SCRK")){
			billType = "SCCK";//销售退货单
		}
		//委外退货单
		if(storageSource.getBillType().equals("WWRK")){
			billType = "WWCK";//销售退货单
		}
		//生产退料
		if(storageSource.getBillType().equals("SCFL")){
			billType = "SCTL";//销售退货单
		}
		//委外退料
		if(storageSource.getBillType().equals("WWFL")){
			billType = "WWTL";//销售退货单
		}
		String enterpriseNo = storageSource.getEnterpriseNo();
		
		Map<String,Object> map = settingService.getBillParam(billType, enterpriseNo);
		String billTypeName = (String) map.get("billTypeName");
		String systemCode = (String) map.get("systemCode");
//		int flowType = (int) map.get("flowType");
		String revOpay = (String) map.get("revOpay");
		int direction = (int) map.get("direction");
		int dealType = (int) map.get("dealType");
		String costingCode = (String) map.get("costingCode");
		String autoCode = (String) map.get("autoCode");
		String origin = (String) map.get("origin");
		String originName = (String) map.get("originName");
		String billNo = (String) map.get("billNo");

		StorageRecord storageRecord = null;
		List<StorageRecordDetail> storageRecordDetails = null;

		//打包主表
		//来源单据
//		StorageRecord storageSource = null;
//		storageSource = storageRecordService.getByID(billID);

		//		String enterpriseNo = storageSource.getEnterpriseNo();//SecurityService.getCurrentOgn().getsFID();
		String enterpriseName = storageSource.getEnterpriseName();//SecurityService.getCurrentOgn().getsName();
		
//		storageRecord = storageRecordService.packing(newBillType, cUsercode, cUsername, userId, enterpriseNo, enterpriseName);
		storageRecord = storageRecordService.packing(billType, billTypeName, systemCode, flowType, revOpay, direction, dealType, costingCode, autoCode, origin, originName, billNo, cUsercode, cUsername, userId, enterpriseNo, enterpriseName);
		
		
		//发货日期
//			if(orderDate!=null && !orderDate.equals("")){
//				storageRecord.setOrderDate(Date.valueOf(orderDate));
//			}
		storageRecord.setComments("系统生成");
		
		//来源单据：销售发货单
		storageRecord.setOrigin(storageSource.getBillType());
		storageRecord.setOriginName(storageSource.getBillTypeName());
		storageRecord.setOriginNo(storageSource.getRecordNo());
		
		storageRecord.setFactoryID(storageSource.getFactoryID());
		storageRecord.setFactoryNo(storageSource.getFactoryNo());
		storageRecord.setFactoryName(storageSource.getFactoryName());
		
		storageRecord.setEmployeeNo(storageSource.getEmployeeNo());
		storageRecord.setEmployeeName(storageSource.getEmployeeName());
		
		storageRecord.setStorageTypeD(storageSource.getStorageTypeD());
		storageRecord.setStorageTypeDLabel(storageSource.getStorageTypeDLabel());
		storageRecord.setProviderID(storageSource.getProviderID());
		storageRecord.setProviderNo(storageSource.getProviderNo());
		storageRecord.setShortName(storageSource.getShortName());
		storageRecord.setProviderName(storageSource.getProviderName());
		
		storageRecord.setStorageType(storageSource.getStorageType());
		storageRecord.setStorageTypeLabel(storageSource.getStorageTypeLabel());
		storageRecord.setStorageID(storageSource.getStorageID());
		storageRecord.setStorageNo(storageSource.getStorageNo());
		storageRecord.setStorageName(storageSource.getStorageName());
		storageRecord.setFloorNo(storageSource.getFloorNo());
		
		storageRecord.setTaxType(storageSource.getTaxType());
		storageRecord.setTaxTypeLabel(storageSource.getTaxTypeLabel());
		storageRecord.setTaxRate(storageSource.getTaxRate());
		
		storageRecord.setInvoiceCategory(storageSource.getInvoiceCategory());
		storageRecord.setInvoiceCategoryLabel(storageSource.getInvoiceCategoryLabel());
		storageRecord.setSettleCategory(storageSource.getSettleCategory());
		storageRecord.setSettleCategoryLabel(storageSource.getSettleCategoryLabel());
		
		storageRecord.setOrderNo(storageSource.getOrderNo());
		
		storageRecord.setfAddress(storageSource.getfAddress());
		storageRecord.setfAddressDetail(storageSource.getfAddressDetail());
		storageRecord.setContacts(storageSource.getContacts());
		storageRecord.setMobilePhone(storageSource.getMobilePhone());
		storageRecord.setfPhone(storageSource.getfPhone());
		
		storageRecord.setOrderWeight(storageSource.getOrderWeight());
		storageRecord.setOrderSize(storageSource.getOrderSize());
		
		storageRecord.setDiscountAmount(storageSource.getDiscountAmount());
		storageRecord.setDiscountRate(storageSource.getDiscountRate());
		
		
//			storageRecord.setResultStatus("待审核");
//			storageRecord.setPaymentStatus("待开票");
		
		
		//子表
		List<StorageRecordDetail> storageSourceDetails = storageRecordDetailService.getByMasterID(storageSource.getfID());
		if(storageSourceDetails.size()>0){
			storageRecordDetails = new ArrayList<StorageRecordDetail>();
		}
		for(StorageRecordDetail storageSourceDetail : storageSourceDetails){
			StorageRecordDetail storageRecordDetail = storageRecordDetailService.packing(storageRecord);
			storageRecord.setMaxDetailNo(storageRecord.getMaxDetailNo()+1);
			storageRecord.setDetailsCount(storageRecord.getDetailsCount()+1);
			
			storageRecordDetail.setOrigin(storageSourceDetail.getBillType());
			storageRecordDetail.setOriginName(storageSourceDetail.getBillTypeName());
			storageRecordDetail.setOriginNo(storageSourceDetail.getRecordNo());
			storageRecordDetail.setOriginSerialNo(storageSourceDetail.getSerialNo());
			
			//物料
			storageRecordDetail.setItemID(storageSourceDetail.getItemID());
			storageRecordDetail.setItemNo(storageSourceDetail.getItemNo());
			storageRecordDetail.setItemName(storageSourceDetail.getItemName());
			storageRecordDetail.setItemProperty(storageSourceDetail.getItemProperty());
			storageRecordDetail.setUnitCode(storageSourceDetail.getUnitCode());
			storageRecordDetail.setUnitName(storageSourceDetail.getUnitName());
			
			FileItem fileItem = fileItemService.getByID(storageRecordDetail.getItemID());

//			storageRecordDetail.setProcess(fileItem.getProcess());
//			storageRecordDetail.setProcessLabel(fileItem.getProcessLabel());
			storageRecordDetail.setQualityType(fileItem.getQualityType());
			storageRecordDetail.setQualityTypeLabel(fileItem.getQualityTypeLabel());
			//处理检验状态/////////////////////////////////////////////////////////
			int qualityType = fileItem.getQualityType();
			if(qualityType==0){
				storageRecordDetail.setQualityStatus(0);
				storageRecordDetail.setQualityStatusLabel("0.免检");
			}else{
				storageRecordDetail.setQualityStatus(1);
				storageRecordDetail.setQualityStatusLabel("1:待验");
			}
			////////////////////////////////////////////////////////////////////////
			
			storageRecordDetail.setMaterialType(1);
			storageRecordDetail.setMaterialTypeLabel("1.直接材料");
			
			//单价
			storageRecordDetail.setItemPrice(storageSourceDetail.getItemPrice());
			storageRecordDetail.setDiscountRate(storageSourceDetail.getDiscountRate());
			//数量
			storageRecordDetail.setItemAmount(storageSourceDetail.getItemAmount());
			storageRecordDetail.setArriveAmount(storageSourceDetail.getItemAmount());
			storageRecordDetail.setPriceAmount(storageSourceDetail.getItemAmount());
			//件数
			storageRecordDetail.setPieceQuantity(storageSourceDetail.getPieceQuantity());
			
			///////////////////////////////////////////////////////////////
			storageRecordDetail.setPiecePackage(storageSourceDetail.getPiecePackage());
			storageRecordDetail.setDiscountAmount(storageSourceDetail.getDiscountAmount());
			storageRecordDetail.setTaxType(storageSourceDetail.getTaxType());
			storageRecordDetail.setTaxTypeLabel(storageSourceDetail.getTaxTypeLabel());
			storageRecordDetail.setTaxRate(storageSourceDetail.getTaxRate());
			
			storageRecordDetail.setSbomID(storageSourceDetail.getSbomID());
			storageRecordDetail.setLv(storageSourceDetail.getLv());
			storageRecordDetail.setSttts(storageSourceDetail.getSttts());
			storageRecordDetail.setCheckin(storageSourceDetail.getCheckin());
			/////////////////////////////////////////////////////////////////
			
			storageRecordDetail.setOrderAmount(storageSourceDetail.getOrderAmount());
			storageRecordDetail.setOrderAmountOld(storageSourceDetail.getOrderAmountOld());
			storageRecordDetail.setOrderAmountTax(storageSourceDetail.getOrderAmountTax());
			storageRecordDetail.setOrderAmountTotal(storageSourceDetail.getOrderAmountTotal());
			
			storageRecordDetail.setStorageType(storageSourceDetail.getStorageType());
			storageRecordDetail.setStorageTypeLabel(storageSourceDetail.getStorageTypeLabel());
			storageRecordDetail.setStorageID(storageSourceDetail.getStorageID());
			storageRecordDetail.setStorageNo(storageSourceDetail.getStorageNo());
			storageRecordDetail.setStorageName(storageSourceDetail.getStorageName());
			storageRecordDetail.setFloorNo(storageSourceDetail.getFloorNo());
			
//			int direction = storageRecord.getDirection();
//			BigDecimal bgDirection = new BigDecimal(direction);
			
//			String revOpay = storageSourceDetail.getRevOpay();
			if(revOpay.equals("I")){
				//入库方向
				
				//账数量，保留两位小数
//				BigDecimal accountQuantityI = storageRecordDetail.getPriceAmount().multiply(bgDirection);
//				accountQuantityI = accountQuantityI.setScale(2, BigDecimal.ROUND_HALF_UP);
//				storageRecordDetail.setAccountQuantityI(accountQuantityI);
				//件数
//				BigDecimal pieceQuantityI = storageRecordDetail.getPieceQuantity().multiply(bgDirection);
//				pieceQuantityI = pieceQuantityI.setScale(2, BigDecimal.ROUND_HALF_UP);
//				storageRecordDetail.setPieceQuantityI(pieceQuantityI);
				
			}
			if(revOpay.equals("O")){
				//出库方向
				//账数量，保留两位小数
//				BigDecimal accountQuantityO = storageRecordDetail.getPriceAmount().multiply(bgDirection);
//				accountQuantityO = accountQuantityO.divide(BigDecimal.ONE, 2, BigDecimal.ROUND_HALF_UP);
//				storageRecordDetail.setAccountQuantityO(accountQuantityO);
				//件数
//				BigDecimal pieceQuantityO = storageRecordDetail.getPieceQuantity().multiply(bgDirection);
//				pieceQuantityO = pieceQuantityO.divide(BigDecimal.ONE, 2, BigDecimal.ROUND_HALF_UP);
//				storageRecordDetail.setPieceQuantityO(pieceQuantityO);
				
			}
			
			//即时成本计算（暂时不做）
//			storageRecordDetail.setMaterialAmountPer(storageSourceDetail.getMaterialAmountPer());
//			storageRecordDetail.setWorkingAmountPer(storageSourceDetail.getWorkingAmountPer());
//			storageRecordDetail.setManufactAmountPer(storageSourceDetail.getManufactAmountPer());
//			storageRecordDetail.setProcessAmountPer(storageSourceDetail.getProcessAmountPer());
//			storageRecordDetail.setCostingAmountPer(storageSourceDetail.getCostingAmountPer());
			
//			BigDecimal materialAmount = storageSourceDetail.getMaterialAmount().multiply(bgDirection);
//			BigDecimal workingAmount = storageSourceDetail.getWorkingAmount().multiply(bgDirection);
//			BigDecimal manufactAmount = storageSourceDetail.getManufactAmount().multiply(bgDirection);
//			BigDecimal processAmount = storageSourceDetail.getProcessAmount().multiply(bgDirection);
//			BigDecimal costingAmount = storageSourceDetail.getCostingAmount().multiply(bgDirection);

//			materialAmount = materialAmount.divide(BigDecimal.ONE, 2, BigDecimal.ROUND_HALF_UP);
//			workingAmount = workingAmount.divide(BigDecimal.ONE, 2, BigDecimal.ROUND_HALF_UP);
//			manufactAmount = manufactAmount.divide(BigDecimal.ONE, 2, BigDecimal.ROUND_HALF_UP);
//			processAmount = processAmount.divide(BigDecimal.ONE, 2, BigDecimal.ROUND_HALF_UP);
//			costingAmount = costingAmount.divide(BigDecimal.ONE, 2, BigDecimal.ROUND_HALF_UP);
			
//			storageRecordDetail.setMaterialAmount(materialAmount);
//			storageRecordDetail.setWorkingAmount(workingAmount);
//			storageRecordDetail.setManufactAmount(manufactAmount);
//			storageRecordDetail.setProcessAmount(processAmount);
//			storageRecordDetail.setCostingAmount(costingAmount);
			
			
			storageRecordDetail.setBatchNo(storageSourceDetail.getBatchNo());
			storageRecordDetail.setBatchDescribe(storageSourceDetail.getBatchDescribe());
			storageRecordDetail.setStoreNo(storageSourceDetail.getStoreNo());
			
			storageRecordDetail.setOrderNo(storageSourceDetail.getOrderNo());
			
			//瞎聊尺寸
			storageRecordDetail.setBlankSize(storageSourceDetail.getBlankSize());
			storageRecordDetail.setWorkNo(storageSourceDetail.getWorkNo());
			storageRecordDetail.setProcedureStep(storageSourceDetail.getProcedureStep());
			
			storageRecordDetail.setDevolveCause(storageSourceDetail.getDevolveCause());
			storageRecordDetail.setDevolveCauseLabel(storageSourceDetail.getDevolveCauseLabel());
			
			storageRecordDetail.setQualityPeriod(storageSourceDetail.getQualityPeriod());
			storageRecordDetail.setProduceDate(storageSourceDetail.getProduceDate());
			storageRecordDetail.setValidDate(storageSourceDetail.getValidDate());
			storageRecordDetail.setCheckoutAgainDate(storageSourceDetail.getCheckoutAgainDate());
			storageRecordDetail.setBrand(storageSourceDetail.getBrand());
			storageRecordDetail.setBrandLabel(storageSourceDetail.getBrandLabel());
			storageRecordDetail.setPlaceOrigin(storageSourceDetail.getPlaceOrigin());
			storageRecordDetail.setManufacturer(storageSourceDetail.getManufacturer());
			storageRecordDetail.setItemWeight(storageSourceDetail.getItemWeight());
			storageRecordDetail.setItemSize(storageSourceDetail.getItemSize());
			storageRecordDetail.setOrderWeight(storageSourceDetail.getOrderWeight());
			storageRecordDetail.setOrderSize(storageSourceDetail.getOrderSize());
			
			//运费及其他费用
			storageRecordDetail.setApportionAmount(storageSourceDetail.getApportionAmount());
			//重量体积
			storageRecordDetail.setItemWeight(storageSourceDetail.getItemWeight());
			storageRecordDetail.setItemSize(storageSourceDetail.getItemSize());
			storageRecordDetail.setOrderWeight(storageSourceDetail.getOrderWeight());
			storageRecordDetail.setOrderSize(storageSourceDetail.getOrderSize());
		
			//累计主表合计金额
			storageRecord.setItemAmount(storageRecord.getItemAmount().add(storageRecordDetail.getItemAmount()));
			storageRecord.setOrderAmount(storageRecord.getOrderAmount().add(storageRecordDetail.getOrderAmount()));
			storageRecord.setOrderAmountOld(storageRecord.getOrderAmountOld().add(storageRecordDetail.getOrderAmountOld()));
			storageRecord.setOrderAmountTax(storageRecord.getOrderAmountTax().add(storageRecordDetail.getOrderAmountTax()));
			storageRecord.setOrderAmountTotal(storageRecord.getOrderAmountTotal().add(storageRecordDetail.getOrderAmountTotal()));
			
			storageRecordDetails.add(storageRecordDetail);
		}
		
		
		//插入主表
		if(storageRecord!=null){
			storageRecordService.insert(storageRecord);
			//插入子表
			if(storageRecordDetails!=null){
				for(StorageRecordDetail storageRecordDetail : storageRecordDetails){
					storageRecordDetailService.insert(storageRecordDetail);
				}
			}
		}
		return storageRecord;
	}

	
	////////////////////////////////////////////////////////////////////////////////////////
	

	

	
	
	
	
	
	
	
	
	
	
	
	
	
	////////////////////////////////////////////////////////////////////////////////////////



	@Transactional
	@Override
	public int updateDevolveCause(JSONObject params){
		String fID = params.getString("fID");
		String devolveCause = params.getString("devolveCause");
		String devolveCauseLabel = params.getString("devolveCauseLabel");
		return storageRecordDetailService.updateDevolveCause(fID, devolveCause, devolveCauseLabel);
	}

	//划菜
	@Transactional
	@Override
	public int updateMaterialType(JSONObject params){
		String fID = params.getString("fID");
		int materialType = params.getIntValue("materialType");
		String materialTypeLabel = params.getString("materialTypeLabel");
		return storageRecordDetailService.updateMaterialType(fID, materialType, materialTypeLabel);
	}
	

	
	//////////////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////
	/////////////////////////////////////////////////////////////////////////////////////

	
	
	@Transactional
	@Override
	public Map<String,Object> stocktakingConfirm(String fID) {
		Stocktaking obj = stocktakingService.getByID(fID);
		MapMessage mapMessage = new MapMessage(obj.getfID(),obj.getDocumentNo(),obj.getBillType(),obj.getBillTypeName()
				,MapMessage.STATUSINFO_SUCCESS_CODE//"http://www.iune.cn"
				,MapMessage.STATUSINFO_SUCCESS_MSG//"操作成功！"
				,MapMessage.STATUSINFO_SUCCESS_INFO//"操作成功！"
				,MapMessage.STATUSINFO_SUCCESS_FLAG//"success"
				);
		
		//主表
		stocktakingService.confirm(fID);
		
		//从表
		stocktakingDetailService.confirmByMasterID(fID);
		
		return mapMessage.toMap();
	}
	
	@Transactional
	@Override
	public Map<String,Object> stocktakingActive(String fID) {
		Stocktaking obj = stocktakingService.getByID(fID);
		MapMessage mapMessage = new MapMessage(obj.getfID(),obj.getDocumentNo(),obj.getBillType(),obj.getBillTypeName()
				,MapMessage.STATUSINFO_SUCCESS_CODE//"http://www.iune.cn"
				,MapMessage.STATUSINFO_SUCCESS_MSG//"操作成功！"
				,MapMessage.STATUSINFO_SUCCESS_INFO//"操作成功！"
				,MapMessage.STATUSINFO_SUCCESS_FLAG//"success"
				);
		//主表
		stocktakingService.active(fID);
		
		//从表
		stocktakingDetailService.activeByMasterID(fID);
		return mapMessage.toMap();
	}
	
	@Transactional
	@Override
	public Map<String,Object> stocktakingAgreeIt(String fID,String usercode,String username, String userId) {
		Stocktaking obj = stocktakingService.getByID(fID);
		MapMessage mapMessage = new MapMessage(obj.getfID(),obj.getDocumentNo(),obj.getBillType(),obj.getBillTypeName()
				,MapMessage.STATUSINFO_SUCCESS_CODE//"http://www.iune.cn"
				,MapMessage.STATUSINFO_SUCCESS_MSG//"操作成功！"
				,MapMessage.STATUSINFO_SUCCESS_INFO//"操作成功！"
				,MapMessage.STATUSINFO_SUCCESS_FLAG//"success"
				);
		//主表
		stocktakingService.agreeIt(fID, usercode, username, userId);
		
		//从表
		stocktakingDetailService.agreeItByMasterID(fID);
		return mapMessage.toMap();
	}
	
	@Transactional
	@Override
	public Map<String,Object> stocktakingUnAgree(String fID) {
		Stocktaking obj = stocktakingService.getByID(fID);
		MapMessage mapMessage = new MapMessage(obj.getfID(),obj.getDocumentNo(),obj.getBillType(),obj.getBillTypeName()
				,MapMessage.STATUSINFO_SUCCESS_CODE//"http://www.iune.cn"
				,MapMessage.STATUSINFO_SUCCESS_MSG//"操作成功！"
				,MapMessage.STATUSINFO_SUCCESS_INFO//"操作成功！"
				,MapMessage.STATUSINFO_SUCCESS_FLAG//"success"
				);
		//主表
		stocktakingService.unAgree(fID);
		
		//从表
		stocktakingDetailService.unAgreeByMasterID(fID);
		return mapMessage.toMap();
	}
	
	@Transactional
	@Override
	public Map<String,Object> stocktakingClose(String fID) {
		Stocktaking obj = stocktakingService.getByID(fID);
		MapMessage mapMessage = new MapMessage(obj.getfID(),obj.getDocumentNo(),obj.getBillType(),obj.getBillTypeName()
				,MapMessage.STATUSINFO_SUCCESS_CODE//"http://www.iune.cn"
				,MapMessage.STATUSINFO_SUCCESS_MSG//"操作成功！"
				,MapMessage.STATUSINFO_SUCCESS_INFO//"操作成功！"
				,MapMessage.STATUSINFO_SUCCESS_FLAG//"success"
				);
		//主表
		stocktakingService.close(fID);
		
		//从表
		stocktakingDetailService.closeByMasterID(fID);
		return mapMessage.toMap();
	}

	
	@Transactional
	@Override
	public Map<String,Object> stocktakingOpen(String fID) {
		Stocktaking obj = stocktakingService.getByID(fID);
		MapMessage mapMessage = new MapMessage(obj.getfID(),obj.getDocumentNo(),obj.getBillType(),obj.getBillTypeName()
				,MapMessage.STATUSINFO_SUCCESS_CODE//"http://www.iune.cn"
				,MapMessage.STATUSINFO_SUCCESS_MSG//"操作成功！"
				,MapMessage.STATUSINFO_SUCCESS_INFO//"操作成功！"
				,MapMessage.STATUSINFO_SUCCESS_FLAG//"success"
				);
		//主表
		stocktakingService.open(fID);
		
		//从表
		stocktakingDetailService.openByMasterID(fID);
		return mapMessage.toMap();
	}

	
	
	//生成盘点单
	@Override
	@Transactional
	public JSONObject stocktakingGenerate(String documentNo, int method, String cUsercode, String cUsername, String userId, String enterpriseNo, String enterpriseName){
		
		JSONObject json = new JSONObject();
		System.out.println("documentNo-->"+documentNo);
		//首先判断单号是否已经存在
		Stocktaking stocktaking = stocktakingService.getByNo(documentNo, enterpriseNo);
		if(stocktaking!=null) {
			json.put("code", 1);
			json.put("msg", "failure");
			json.put("info", "单号已经存在！");
			return json;
		}
	
		String billType, billTypeName, systemCode;
		billType = "PDDJ";
		billTypeName = "盘点清单";
		systemCode = null;
		//插入主表
		stocktaking = stocktakingService.packing(billType, billTypeName, systemCode, cUsercode, cUsername, userId, enterpriseNo, enterpriseName);
		stocktaking.setDocumentNo(documentNo);
		//最后插入
		//stocktakingService.insert(stocktaking);
		
		int x = 0;
		int y = 0;
		switch(method) {
		case 0:
			//按仓库
			//获取仓库列表
			List<FileStorage> fileStorages = fileStorageService.getRoots(enterpriseNo);
			System.out.println("仓库数量：-->"+fileStorages.size());
			for(FileStorage fileStorage: fileStorages) {
				//循环仓库
				String storageType = fileStorage.getStorageType();
				String storageTypeLabel = fileStorage.getStorageTypeLabel();
				String storageNo = fileStorage.getStorageNo();
				String storageName = fileStorage.getStorageName();

				String factoryID = fileStorage.getFactoryID();
				String factoryNo = fileStorage.getFactoryNo();
				String factoryName = fileStorage.getFactoryName();

				String storehouseID = fileStorage.getfID();
				List<StorageItem> storageItems = storageItemService.getList(storehouseID, enterpriseNo);
				//循环物料仓库档案，取出物料
				for(StorageItem storageItem: storageItems) {
					x++;
					String itemID = storageItem.getItemID();
					//判断是否启用了批号管理
			        FileItem fileItem = fileItemService.getByID(itemID);
					String itemNo = fileItem.getItemNo();
					String itemName = fileItem.getItemName();
					String itemProperty = fileItem.getItemProperty();
					String unitCode = fileItem.getUnitCode();
					String unitName = fileItem.getUnitName();
					String batchNo = fileItem.getBatchNo();
					
					//库位ID
					String storageID = storageItem.getStorageID();
					FileStorage fileFloor = fileStorageService.getByID(storageID);
					String floorNo = fileFloor.getStorageFullName();
					
					
					String batchDescribe = null;
					//账面数量
					BigDecimal bookQuantity = storageItem.getItemQuantityL();
					//账面包装数量
					BigDecimal bookPackage = storageItem.getPieceQuantityL();

					//是否启用批号管理
					if("********************".equals(batchNo)){
						//未启用
						int batchFlag = 0;
						/////////////////////////////////////////////
						StocktakingDetail stocktakingDetail = stocktakingDetailService.packing(stocktaking);
						//物料
						stocktakingDetail.setItemID(itemID);
						stocktakingDetail.setItemNo(itemNo);
						stocktakingDetail.setItemName(itemName);
						stocktakingDetail.setItemProperty(itemProperty);
						stocktakingDetail.setUnitCode(unitCode);
						stocktakingDetail.setUnitName(unitName);
						stocktakingDetail.setBatchFlag(batchFlag);
						stocktakingDetail.setBatchNo(batchNo);
						stocktakingDetail.setBatchDescribe(batchDescribe);
						//仓库
						stocktakingDetail.setStorageType(storageType);
						stocktakingDetail.setStorageTypeLabel(storageTypeLabel);
						stocktakingDetail.setStorageNo(storageNo);
						stocktakingDetail.setStorageName(storageName);
						stocktakingDetail.setFloorNo(floorNo);
						stocktakingDetail.setStorageID(storageID);
						stocktakingDetail.setStorehouseID(storehouseID);
						stocktakingDetail.setFactoryID(factoryID);
						stocktakingDetail.setFactoryNo(factoryNo);
						stocktakingDetail.setFactoryName(factoryName);
						stocktakingDetail.setBookQuantity(bookQuantity);
						stocktakingDetail.setBookPackage(bookPackage);
						//插入
						stocktakingDetailService.insert(stocktakingDetail);
						//主表记录数增加
						stocktaking.setMaxDetailNo(stocktaking.getMaxDetailNo()+1);
						stocktaking.setDetailsCount(stocktaking.getDetailsCount()+1);
						//////////////////////////////////////////////
						y++;
			        }else {
			        	//已启用批号管理，库存数量需取自批次库存数量
						int batchFlag = 1;
						List<StorageItemBatch> list = storageItemBatchService.getList(storehouseID, itemID, enterpriseNo);
			        	//循环
			        	for(StorageItemBatch storageItemBatch: list) {
			        		batchNo = storageItemBatch.getBatchNo();
			        		ItemBatch itemBatch = itemBatchService.getByNo(itemID, batchNo, enterpriseNo);
			        		if(itemBatch==null) {
			        			batchDescribe = "批号档案不存在，这是一个错误！";
			        		}else {
				        		batchDescribe = itemBatch.getBatchDescribe();
			        		}
			        	
							//账面数量
							bookQuantity = storageItemBatch.getItemQuantityL();
							//账面包装数量
							bookPackage = storageItemBatch.getPieceQuantityL();
							/////////////////////////////////////////////
							StocktakingDetail stocktakingDetail = stocktakingDetailService.packing(stocktaking);
							//物料
							stocktakingDetail.setItemID(itemID);
							stocktakingDetail.setItemNo(itemNo);
							stocktakingDetail.setItemName(itemName);
							stocktakingDetail.setItemProperty(itemProperty);
							stocktakingDetail.setUnitCode(unitCode);
							stocktakingDetail.setUnitName(unitName);
							stocktakingDetail.setBatchFlag(batchFlag);
							stocktakingDetail.setBatchNo(batchNo);
							stocktakingDetail.setBatchDescribe(batchDescribe);
							//仓库
							stocktakingDetail.setStorageType(storageType);
							stocktakingDetail.setStorageTypeLabel(storageTypeLabel);
							stocktakingDetail.setStorageNo(storageNo);
							stocktakingDetail.setStorageName(storageName);
							stocktakingDetail.setFloorNo(floorNo);
							stocktakingDetail.setStorageID(storageID);
							stocktakingDetail.setStorehouseID(storehouseID);
							stocktakingDetail.setFactoryID(factoryID);
							stocktakingDetail.setFactoryNo(factoryNo);
							stocktakingDetail.setFactoryName(factoryName);
							stocktakingDetail.setBookQuantity(bookQuantity);
							stocktakingDetail.setBookPackage(bookPackage);
							//插入
							stocktakingDetailService.insert(stocktakingDetail);
							//主表记录数增加
							stocktaking.setMaxDetailNo(stocktaking.getMaxDetailNo()+1);
							stocktaking.setDetailsCount(stocktaking.getDetailsCount()+1);
							//////////////////////////////////////////////
							y++;
			        	}
			        }
				}
			}
			break;
		case 1:
			//按物料
			List<FileItem> fileItems = fileItemService.getList(enterpriseNo);
			for(FileItem fileItem: fileItems) {
				//循环物料
				x++;
				//判断是否启用了批号管理
				String itemID = fileItem.getfID();
				String itemNo = fileItem.getItemNo();
				String itemName = fileItem.getItemName();
				String itemProperty = fileItem.getItemProperty();
				String unitCode = fileItem.getUnitCode();
				String unitName = fileItem.getUnitName();
				String batchNo = fileItem.getBatchNo();
				
				String batchDescribe = null;
				//账面数量
				BigDecimal bookQuantity = BigDecimal.ZERO;
				//账面包装数量
				BigDecimal bookPackage = BigDecimal.ZERO;

				//是否启用批号管理
				if("********************".equals(batchNo)){
					//未启用
					int batchFlag = 0;
					List<StorageItem> storageItems = storageItemService.getByItemID(itemID, enterpriseNo);
					//循环物料仓库档案，取出物料
					for(StorageItem storageItem: storageItems) {
						String storageID = storageItem.getStorageID();
						FileStorage fileFloor = fileStorageService.getByID(storageID);
						String storageType = fileFloor.getStorageType();
						String storageTypeLabel = fileFloor.getStorageTypeLabel();
						String storageNo = fileFloor.getStorageNo();
						String storageName = fileFloor.getStorageName();

						String factoryID = fileFloor.getFactoryID();
						String factoryNo = fileFloor.getFactoryNo();
						String factoryName = fileFloor.getFactoryName();

						String storehouseID = storageItem.getStorehouseID();
						String floorNo = fileFloor.getStorageFullName();
						
						//账面数量
						bookQuantity = storageItem.getItemQuantityL();
						//账面包装数量
						bookPackage = storageItem.getPieceQuantityL();
						
						/////////////////////////////////////////////
						StocktakingDetail stocktakingDetail = stocktakingDetailService.packing(stocktaking);
						//物料
						stocktakingDetail.setItemID(itemID);
						stocktakingDetail.setItemNo(itemNo);
						stocktakingDetail.setItemName(itemName);
						stocktakingDetail.setItemProperty(itemProperty);
						stocktakingDetail.setUnitCode(unitCode);
						stocktakingDetail.setUnitName(unitName);
						stocktakingDetail.setBatchFlag(batchFlag);
						stocktakingDetail.setBatchNo(batchNo);
						stocktakingDetail.setBatchDescribe(batchDescribe);
						//仓库
						stocktakingDetail.setStorageType(storageType);
						stocktakingDetail.setStorageTypeLabel(storageTypeLabel);
						stocktakingDetail.setStorageNo(storageNo);
						stocktakingDetail.setStorageName(storageName);
						stocktakingDetail.setFloorNo(floorNo);
						stocktakingDetail.setStorageID(storageID);
						stocktakingDetail.setStorehouseID(storehouseID);
						stocktakingDetail.setFactoryID(factoryID);
						stocktakingDetail.setFactoryNo(factoryNo);
						stocktakingDetail.setFactoryName(factoryName);
						stocktakingDetail.setBookQuantity(bookQuantity);
						stocktakingDetail.setBookPackage(bookPackage);
						//插入
						stocktakingDetailService.insert(stocktakingDetail);
						//主表记录数增加
						stocktaking.setMaxDetailNo(stocktaking.getMaxDetailNo()+1);
						stocktaking.setDetailsCount(stocktaking.getDetailsCount()+1);
						//////////////////////////////////////////////
						y++;
					}
				}else {
		        	//已启用批号管理，库存数量需取自批次库存数量
					int batchFlag = 1;
					List<StorageItemBatch> list = storageItemBatchService.getByItemID(itemID, enterpriseNo);
		        	//循环
		        	for(StorageItemBatch storageItemBatch: list) {
		        		batchNo = storageItemBatch.getBatchNo();
		        		ItemBatch itemBatch = itemBatchService.getByNo(itemID, batchNo, enterpriseNo);
		        		if(itemBatch==null) {
		        			batchDescribe = "批号档案不存在，这是一个错误！";
		        		}else {
			        		batchDescribe = itemBatch.getBatchDescribe();
		        		}
		        		
						String storageID = storageItemBatch.getStorageID();
						FileStorage fileFloor = fileStorageService.getByID(storageID);
						String storageType = fileFloor.getStorageType();
						String storageTypeLabel = fileFloor.getStorageTypeLabel();
						String storageNo = fileFloor.getStorageNo();
						String storageName = fileFloor.getStorageName();

						String factoryID = fileFloor.getFactoryID();
						String factoryNo = fileFloor.getFactoryNo();
						String factoryName = fileFloor.getFactoryName();

						String storehouseID = storageItemBatch.getStorehouseID();
						String floorNo = fileFloor.getStorageFullName();
		        	
						//账面数量
						bookQuantity = storageItemBatch.getItemQuantityL();
						//账面包装数量
						bookPackage = storageItemBatch.getPieceQuantityL();
						/////////////////////////////////////////////
						StocktakingDetail stocktakingDetail = stocktakingDetailService.packing(stocktaking);
						//物料
						stocktakingDetail.setItemID(itemID);
						stocktakingDetail.setItemNo(itemNo);
						stocktakingDetail.setItemName(itemName);
						stocktakingDetail.setItemProperty(itemProperty);
						stocktakingDetail.setUnitCode(unitCode);
						stocktakingDetail.setUnitName(unitName);
						stocktakingDetail.setBatchFlag(batchFlag);
						stocktakingDetail.setBatchNo(batchNo);
						stocktakingDetail.setBatchDescribe(batchDescribe);
						//仓库
						stocktakingDetail.setStorageType(storageType);
						stocktakingDetail.setStorageTypeLabel(storageTypeLabel);
						stocktakingDetail.setStorageNo(storageNo);
						stocktakingDetail.setStorageName(storageName);
						stocktakingDetail.setFloorNo(floorNo);
						stocktakingDetail.setStorageID(storageID);
						stocktakingDetail.setStorehouseID(storehouseID);
						stocktakingDetail.setFactoryID(factoryID);
						stocktakingDetail.setFactoryNo(factoryNo);
						stocktakingDetail.setFactoryName(factoryName);
						stocktakingDetail.setBookQuantity(bookQuantity);
						stocktakingDetail.setBookPackage(bookPackage);
						//插入
						stocktakingDetailService.insert(stocktakingDetail);
						//主表记录数增加
						stocktaking.setMaxDetailNo(stocktaking.getMaxDetailNo()+1);
						stocktaking.setDetailsCount(stocktaking.getDetailsCount()+1);
						//////////////////////////////////////////////
						y++;
		        	}
					
				}
			}
			break;
		default:
			System.out.println("未知类型："+method);
			break;
		}
		
		
		//插入主表记录
		stocktakingService.insert(stocktaking);
		
		String itemStr = "共有"+x+"种物料已盘点。";
		String entryStr = "共有"+y+"条盘点记录生成。";
		System.out.println(itemStr);
		System.out.println(entryStr);
		
		JSONObject data = new JSONObject();
		data.put("itemStr",itemStr);
		data.put("entryStr",entryStr);
		
		json.put("code", 0);
		json.put("msg", "success");
		json.put("data",data);
		return json;
			
	}

	//获取库存数量（前端录入盘点单时使用）
	/* (non-Javadoc)
	 * @see com.iune.erp.inventory.IStorageService#getCheckQuantity(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)
	 */
	@Override
	public Map<String,Object> getCheckQuantity(String storageID,String itemID,String itemProperty,String batchNo,String storeNo,String enterpriseNo){

		Map<String,Object> map =  new HashMap<String, Object>();

		BigDecimal quantityL = BigDecimal.ZERO;
		BigDecimal pieceQuantityL = BigDecimal.ZERO;
		
		String state = "success";
		String source = "";
		
    	//。。。。。。。。。。。。。
    	//无需判断是否启用了库位，直接读取数量即可
    	IStorageItemService siu = new StorageItemServiceImpl();
    	StorageItem si = siu.getByNo(storageID, itemID);
		if (null!=si){
			//读取数量
			//账面数量
	    	quantityL = si.getItemQuantityL();//r.getDecimal("quantityL");
			//账面件数
	    	pieceQuantityL = si.getPieceQuantityL();//r.getDecimal("pieceQuantityL");
			//库存
			source = "StorageItem";

			map.put("state", state);
			map.put("source", source);
			
			map.put("quantityL", quantityL);
			map.put("pieceQuantityL", pieceQuantityL);

			return map;
		}else{
			System.out.println("系统提示-->物料库存档案不存在。");
			//序列号库存
			source = "StorageItem";
			state = "failure";

			map.put("state", state);
			map.put("source", source);
			
			map.put("quantityL", quantityL);
			map.put("pieceQuantityL", pieceQuantityL);
			return map;
		}
		
        
  	}
	
		
	@Override
	public JSONObject responseJSON(String flag,String code,String message) {
		JSONObject response = new JSONObject();
		response.put("flag", flag);
		response.put("code", code);
		response.put("message", message);
		return response;
	}

	
	
	
}
